<?php
/**
* @package Pages-and-Items (com_pi_pages_and_items)
* @version 1.5.7
* @copyright Copyright (C) 2006-2010 Carsten Engel. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
* @author http://www.pages-and-items.com
*/

//no direct access
if(!defined('_VALID_MOS') && !defined('_JEXEC')){
	die('Restricted access');
}

class class_pi{

	var $usergroup;
	var $page_access_rights;
	var $mambot = 0;
	var $plugin = 0;
	var $menuitems;
	var $pi_config;	
	var $current_menutype;	
	var $menutypes = array();
	var $user_access_config;
	var $db;
	var $user_type;
	var $user_id;
	var $live_site;
	var $class_ua = false;	
	var $aua_installed = false;
	var $task;
	var $sub_task;
	var $plugin_dir;
	var $fieldtypes_integrated = array('checkbox','editor','html','image','item_author','item_creation_date','item_modified_date','item_publish_date','item_title','item_version','php','radio','select','text','textarea','calendar','image_multisize');	
	var $version = '1.5.7';	
	var $module_installed = 0;
	var $itemtypes = array();	
	
	function class_pi(){
		//constructor		
		global $database, $my, $task, $sub_task, $mainframe, $mosConfig_live_site;			
		
		//get database
		if( defined('_JEXEC') ){
			//joomla 1.5
			$this->db =& JFactory::getDBO();
		}else{
			//joomla 1.0.x
			$this->db =& $database;
		}
		
		//get things
		$this->pi_config = $this->get_config();			
		$this->task = $task;
		$this->sub_task = $sub_task;			
		
		require_once(dirname(__FILE__).'/language/'.$this->pi_config['language'].'.php');
		
		//reformat cheatsheet config	
		$temp_cheatsheet = $this->pi_config['plugin_syntax_cheatcheat'];	
		
		$temp_cheatsheet = str_replace('[newline]','
',$temp_cheatsheet);
		$temp_cheatsheet = str_replace('[equal]','=',$temp_cheatsheet);
		$this->pi_config['plugin_syntax_cheatcheat'] = $temp_cheatsheet;
		
		//reformat item_save_redirect_url	
		$temp_item_save_redirect_url = $this->pi_config['item_save_redirect_url'];		
		$temp_item_save_redirect_url = str_replace('[equal]','=',$temp_item_save_redirect_url);
		$this->pi_config['item_save_redirect_url'] = $temp_item_save_redirect_url;
		
		//set var user_type and user_id
		if(defined('_JEXEC')){
			//joomla 1.5
			$user =& JFactory::getUser();		
			$this->user_type = $user->get('usertype');
			$user_id = $user->get('id');
		}else{
			//joomla 1.0.x
			$this->user_type = $my->usertype;
			$user_id = $my->id;	
		}
		$this->user_id = $user_id;
		
		//check if mambot is installed		
		if( defined('_JEXEC') ){
			//joomla 1.5
			$this->plugin_dir = 'plugins';
		}else{
			//joomla 1.0.x
			$this->plugin_dir = 'mambots';
		}
		//just checking for the file, don't want an extra query on each page
		if(!file_exists(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/content/pages_and_items.php')){				
			echo '<p class="warning">'._pi_lang_nomambotinstalled.'</p>';			
		}else{
			$this->mambot = 1;//to be used again in item.php
		}	
		
		//check if module is installed	
		if( defined('_JEXEC') ){
			//joomla 1.5
			$mod_dir = 'modules/mod_pages_and_items';
		}else{
			//joomla 1.0.x
			$mod_dir = 'modules';
		}	
		//just checking for the file, don't want an extra query on each page
		if(!file_exists(dirname(__FILE__).'/../../../'.$mod_dir.'/mod_pages_and_items.php')){			
			echo '<p class="warning">'._pi_lang_mod_not_installed.'</p>';			
		}else{
			$this->module_installed = 1;
		}					
		
		//check to see which menutypes we need			
		$menutypes = "AND (";
		$temp_menus = explode(',',$this->pi_config['menus']);		
		for($n = 0; $n < count($temp_menus); $n++){			
			if($n!=0){
				$menutypes .= " OR ";
			}
			$menutype = explode(';',$temp_menus[$n]);			
			$menutypes .= "menutype='".$menutype[0]."'";
			array_push($this->menutypes,$menutype[0]);
			//$menu_array = array($menutype[0],$menutype[1]);
			//array_push($this->menus,$menu_array);
		}		
		$menutypes .= ")";
		
		//itemtypes
		$temp_itemtypes = explode(',',$this->pi_config['itemtypes']);		
		for($n = 0; $n < count($temp_itemtypes); $n++){				
			array_push($this->itemtypes,$temp_itemtypes[$n]);			
		}			
		
		//get menuitems (to be recycled in different functions)
		if( defined('_JEXEC') ){
			//joomla 1.5
			$this->db->setQuery("SELECT id, menutype, published, link, name, alias, type, parent, sublevel, componentid, ordering, browserNav, utaccess, access, params, home FROM #__menu  WHERE (published='0' OR published='1') $menutypes ORDER BY ordering ASC"  );
		}else{
			//joomla 1.0.x			
			$this->db->setQuery("SELECT id, menutype, published, link, name, type, parent, componentid, ordering, browserNav, utaccess, access, params FROM #__menu WHERE (published='0' OR published='1') $menutypes ORDER BY ordering ASC"  );
		}		
		$this->menuitems = $this->db->loadObjectList();		
		
		//get the current pages menutype				
		if(count($temp_menus)!=0){				
			if($task=='root'){
				$menu_in_url = $this->get_var('menutype');
				if(!$menu_in_url){							
					$menu_in_url .= $this->menutypes[0];
				}					
				$this->current_menutype = $menu_in_url;		
			}else{
				foreach($this->menuitems as $menuitem){
					if($menuitem->id==$this->get_var('pageId')){
						$this->current_menutype = $menuitem->menutype;	
						break;				
					}				
				}
			}
		}else{		
			echo '<div class="warning">'._pi_lang_no_menus_selected.'</div>';
		}	
		
		//get live_site
		if( defined('_JEXEC') ){
			//joomla 1.5
			//$this->live_site = $mainframe->getCfg('live_site');
			$this->live_site =$mainframe->isAdmin() ? $mainframe->getSiteURL() : JURI::base();
		}else{
			//joomla 1.0.x
			$this->live_site = $mosConfig_live_site;
		}
		
		//if using user_access component include stuff and get data
		if($this->pi_config['use_user_access_component']){
			
			//check if com_pi_admin_user_access is installed	
			if(file_exists(dirname(__FILE__).'/../com_pi_admin_user_access/admin.pi_admin_user_access.php')){
			
				//Admin-User-Access is installed				
				require_once(dirname(__FILE__).'/../com_pi_admin_user_access/class.php');				
				$this->class_ua = new class_ua();
				$this->aua_installed = true;
				$this->user_access_config = $this->get_config_admin_user_access();
								
				//get usergroup					
				$this->db->setQuery("SELECT group_id FROM #__pi_aua_userindex WHERE user_id='$user_id' LIMIT 1 ");
				$rows = $this->db->loadObjectList();
				if(count($rows) > 0){
					$row = $rows[0];				
					$this->usergroup = $row->group_id;
				}
				
				//get pages and sections array if using section restrictions
				if($this->user_access_config['active_sections'] && $this->user_type!='Super Administrator'){					
					$this->pages_sections_array = $this->class_ua->get_pages_sections_array($this->menuitems);	
					$this->sections_access_array = $this->class_ua->section_access;							
				}
			}else{
				//Admin-User-Acces is not installed
				echo '<p class="warning">'._pi_lang_nouainstalled._pi_lang_configed_to_use_aua.' '._pi_lang_useraccessswitchoff.'</p>';
			}//end if aua is installed	
						
		}//end Admin-User-Access stuff
		
		//check if sections are configured
		$temp_sections = explode(',',$this->pi_config['sections']);		
		if($temp_sections[0]=='' && !$this->pi_config['sections_from_db']){
			echo '<p class="warning">'._pi_lang_nosections.'</p>';	
		}	
			
	}
	
	function get_var($name, $default = null, $hash = 'default', $type = 'none', $mask = 0){	
		//make sure there is no $type
		if($type!='none' && $type!=''){			
			exit('don\'t use $type, it won\'t work in older versions');
		}
		if( defined('_JEXEC') ){
			//joomla 1.5
			$var = JRequest::getVar($name, $default, $hash, $type, $mask);
		}else{
			//joomla 1.0.x
			//do the thing with hash (cake anyone?)
			$hash = strtolower($hash);			
			switch ($hash) {
			case 'default':
				$hash = $_REQUEST;
				break;
			case 'get':
				$hash = $_GET;
				break;
			case 'post':
				$hash = $_POST;
				break;
			case 'files':
				exit('don\'t use FILES, it won\'t work in older versions');
				break;
			case 'method':
				exit('don\'t use METHOD, it won\'t work in older versions');
				break;
			}				
			$var = mosGetParam($hash, $name, $default, $mask);
		}
		return $var;
	}
	
	//display navigation tree
	function pages(){	
		global $pageId, $pi_config;		
		
		if($this->user_type=='Super Administrator'){
			echo '<div id="config_link"><a href="index2.php?option=com_pi_pages_and_items&task=config">'._pi_lang_config.'</a></div>';
		}		
		
		echo "<link href=\"components/com_pi_pages_and_items/css/pages_and_items3.css\" rel=\"stylesheet\" type=\"text/css\" />\n";
		echo "<link href=\"components/com_pi_pages_and_items/css/dtree.css\" rel=\"stylesheet\" type=\"text/css\" />\n";
		if( !defined('_JEXEC') ){//joomla version is 1.0.x so also get those red-like colors
			echo '<link href="../../com_pi_pages_and_items/admin/components/com_pi_pages_and_items/css/joomla_1_0_x.css" rel="stylesheet" type="text/css" />'."\n";
		}  
		echo "<script src=\"components/com_pi_pages_and_items/javascript/dtree.js\" language=\"JavaScript\" type=\"text/javascript\"></script>";
		echo "<script src=\"../includes/js/overlib_mini.js\" language=\"JavaScript\" type=\"text/javascript\"></script>";			
		
		//see how many loops we need
		$loops = count($this->menutypes);	
		
		//loop menutypes
		for($m = 0; $m < $loops; $m++){		
		
			echo '<div class="dtree">';
			echo '<p><a href="javascript: d'.$m.'.openAll();">'._pi_lang_open_all.'</a> | <a href="javascript: d'.$m.'.closeAll();">'._pi_lang_close_all.'</a></p>';	
		
			//open javascript
			echo "<script language=\"javascript\"  type=\"text/javascript\">\n";
			echo "<!--\n";
			echo "d$m = new dTree('d$m');\n";
			echo "d$m.add(0,-1,'";
			echo $this->get_menutype_title($this->menutypes[$m]);			
			echo "','index2.php?option=com_pi_pages_and_items&task=root&menutype=";
			echo strtolower($this->menutypes[$m]);			
			echo "','','','','',true);\n";	
			
			//make javascript-array from menu-items
			foreach($this->menuitems as $row){
				if($row->menutype==$this->menutypes[$m]){
					echo "d$m.add(".$row->id.",".$row->parent.",'".(addslashes($row->name))."','index2.php?option=com_pi_pages_and_items&task=page&sub_task=edit&pageId=".$row->id;
					if(((strstr($row->link, 'index.php?option=com_content&view=category&layout=blog') && $row->type=='url') || !strstr($row->link, 'index.php?option=com_content&view=category&layout=blog')) && $row->type!='content_blog_category'){						
						if($this->pi_config['use_user_access_component'] && ($this->user_access_config['active_pagesaccess'] || $this->user_access_config['active_actions']) && $this->user_type!='Super Administrator'){							
							//if(!in_array($pageAccess, $this->page_access_rights) || !$this->checkUserActionRight(4)){
							if(!$this->check_page_access($row->id) || !$this->checkUserActionRight(4)){
								echo "','','','components/com_pi_pages_and_items/images/link_noaccess.gif','components/com_pi_pages_and_items/images/link_noaccess.gif";
							}else{
								echo "','','','components/com_pi_pages_and_items/images/link.gif','components/com_pi_pages_and_items/images/link.gif";
							}
						}else{
							echo "','','','components/com_pi_pages_and_items/images/link.gif','components/com_pi_pages_and_items/images/link.gif";
						}	
					}else{						
						if($this->pi_config['use_user_access_component'] && ($this->user_access_config['active_pagesaccess'] || $this->user_access_config['active_actions'] || $this->user_access_config['active_sections']) && $this->user_type!='Super Administrator'){							
							//if(!in_array($pageAccess, $this->page_access_rights) || !$this->checkUserActionRight(3) || !$this->check_section_access_by_pageid($row->id)){	
							if(!$this->check_page_access($row->id) || !$this->checkUserActionRight(3) || !$this->check_section_access_by_pageid($row->id)){							
								echo "','','','components/com_pi_pages_and_items/images/page_noaccess.gif','components/com_pi_pages_and_items/images/page_noaccess.gif";	
							}else{
								echo "','','','components/com_pi_pages_and_items/images/page.gif','components/com_pi_pages_and_items/images/page.gif";							
							}
						}else{
							echo "','','','components/com_pi_pages_and_items/images/page.gif','components/com_pi_pages_and_items/images/page.gif";
						}
					}
					echo "');\n";
				}	
			}	
		   
			echo "document.write(d$m);\n";
		
			//if on a certain page, make tree-menu-button selected
			if($this->menutypes[$m]==$this->current_menutype){
				if($pageId){
					echo "d$m.openTo(";
					echo $pageId;
					echo ", true);\n";
				}
			}
		
			//close javascript
			echo "//-->\n";
			echo "</script>\n";
			echo '</div>';		
		
		}//end loops menutype				
	}
	
	//underlyingPages
	function underlyingPages() {
		global $pageId;	
		
		echo '<div class="paddingList"><input type="button" value="'._pi_lang_new_page.'" class="button" style="background: url(components/com_pi_pages_and_items/images/page.gif) no-repeat #d4d0c8 3px 2px;';
		if(!$this->checkUserActionRight(1)){
			echo 'color: grey;'; 
		}
		echo '" title="'._pi_lang_make_new_page.'" onclick="';
		if($this->checkUserActionRight(1)){ 
			echo 'document.location.href=\'index2.php?option=com_pi_pages_and_items&type=content_blog_category&task=page&sub_task=new&pageId='.$pageId.'&menutype='.$this->current_menutype.'\'';
		}else{ 
			echo 'alert(\''._pi_lang_no_new_page.'\');';
		} 
		echo '" />&nbsp;&nbsp;&nbsp;<input type="button" value="'._pi_lang_new_link.'" class="button"  style="background: url(components/com_pi_pages_and_items/images/link.gif) no-repeat #d4d0c8 3px 2px;';
		if(!$this->checkUserActionRight(2)){
			echo 'color: grey;';
		}
		echo '" title="'._pi_lang_make_new_link.'" onclick="';
		
		if($this->checkUserActionRight(2)){ 
			echo 'document.location.href=\'index2.php?option=com_pi_pages_and_items&task=page&sub_task=new&type=url&pageId='.$pageId.'&menutype='.$this->current_menutype.'\'';
		}else{ 
			echo 'alert(\''._pi_lang_no_new_link.'\');';
		}
		echo '" /><br />';			
		
		//hide the data on the page
		echo '<div style="display: none;">';
		
		//headers
		echo '<div id="pagesheader_column_1"><strong>'._pi_lang_title.'</strong></div>';
		echo '<div id="pagesheader_column_2"><strong>'._pi_lang_type.'</strong></div>';		
	
		//loop through items and echo data to hidden fields
		$counter = 0;
		foreach($this->menuitems as $row){
			if($row->parent==$pageId && $row->menutype==$this->current_menutype){
				$areThereUnderlyingPages = true;
				$counter = $counter + 1;			
				$page_title = htmlspecialchars($row->name);	
				
				$no_access = '';			
				
				//check page-access
				if(!$this->check_page_access($row->id)){				
					$no_access = _pi_lang_nopageaccess;
				}
				
				//check workflow access				
				if(((strstr($row->link, 'index.php?option=com_content&view=category&layout=blog') && $row->type=='url') || !strstr($row->link, 'index.php?option=com_content&view=category&layout=blog')) && $row->type!='content_blog_category'){	
					//$pagetype = 'link';
					if(!$this->checkUserActionRight(4)){
						$no_access = _pi_lang_noeditpagelink;
					}
				}else{
					//$pagetype = 'contentblog';
					if(!$this->checkUserActionRight(3)){
						$no_access = _pi_lang_noeditpage;
					}
					if(!$this->check_section_access_by_pageid($row->id)){
						$no_access = _pi_lang_nosectionaccess;
					}
				}
				
				echo '<input name="reorder_page_id_'.$counter.'" id="reorder_page_id_'.$counter.'" type="hidden" value="'.$row->id.'" />';
				
				//column 1					
				echo '<div id="page_column_1_'.$counter.'">';
				if($no_access){				
					echo '<span class="editlinktip" onMouseOver="return overlib(\''.$no_access.'\', CAPTION, \'\', BELOW, RIGHT);" onMouseOut="return nd();" >';
					echo '<img src="components/com_pi_pages_and_items/images/no_access.gif" alt="'.$no_access.'" />';
					echo '</span>&nbsp;';
				}
				echo '<a href="index2.php?option=com_pi_pages_and_items&task=page&sub_task=edit&pageId='.$row->id.'">'.$page_title.'</a>';
				echo '</div>';					
			}			
		}
		echo '</div>';
	
		
		//2 hidden fields which are usefull for updating the ordering when submitted
		echo '<input name="pages_are_reordered" id="pages_are_reordered" type="hidden" value="false" />';
		echo '<input name="pages_total" id="pages_total" type="hidden" value="'.$counter.'" />';
		
		echo '<div id="target_pages"></div>';
		echo '<script src="components/com_pi_pages_and_items/javascript/reorder_pages.js" language="JavaScript" type="text/javascript"></script>';
		echo '<script language="JavaScript"  type="text/javascript">';
		echo "<!--\n";	
		echo "var pages_total = ".$counter.";\n";		
		echo "var number_of_columns_pages = '1';\n";
		echo "var ordering = '"._pi_lang_ordering."';\n";
		echo "var no_pages = '"._pi_lang_thispagenounderlyingpages."';\n";	
		echo "document.onload = print_pages();\n";
		echo "-->\n";
		echo "</script>\n";		
		echo '</div>';		
	}
	
	function items($item_ordering) {
		global $pageId, $pi_config;				
		
		echo '<div class="paddingList">';
		
		//itemtype select and button
		if($this->checkUserActionRight(10)){						
			$this->itemtype_select($pageId);			
		}	
		
		//get category id of menuitem	 and menu_params
		foreach($this->menuitems as $row){
			if($row->id==$pageId){
				$menu_params = $row->params;
				if(defined('_JEXEC')){
					//joomla 1.5
					$cat_id = str_replace('index.php?option=com_content&view=category&layout=blog&id=','',$row->link);
					break;
				}else{	
					//joomla 1.0.x
					$cat_id = $row->componentid;
					break;
				}
			}
		}		
		
		switch ($item_ordering) {
		case 'date':
			$order = 'c.created ASC';
			break;
		case 'rdate':
			$order = 'c.created DESC';
			break;
		case 'alpha':
		default:
			$order = 'c.title ASC';
			break;
		case 'ralpha':
			$order = 'c.title DESC';
			break;
		case 'author':
			$order = 'u.username ASC';
			break;
		case 'rauthor':
			$order = 'u.username DESC';
			break;
		case 'hits':
			$order = 'c.hits ASC';
			break;
		case 'rhits':
			$order = 'c.hits DESC';
			break;
		case 'order':
			$order = 'c.ordering ASC';
			break;
		}	
				
		$this->db->setQuery( "SELECT c.id, c.title, i.itemtype, c.created_by, u.username "
		. "\nFROM #__content AS c "		
		. "\nLEFT JOIN #__pi_item_index AS i ON c.id=i.item_id "
		. "\nLEFT JOIN #__users AS u ON u.id=c.created_by "		
		. "\nWHERE c.catid='$cat_id' "
		. "\nAND (c.state='0' OR c.state='1') "			
		. "\nORDER BY $order "		
		);		
		$rows = $this->db->loadObjectList();		
		
		
		
		//hide the data on the page
		echo '<div style="display: none;">';
		
		//headers
		echo '<div id="header_column_1"><strong>'._pi_lang_title.'</strong></div>';
		echo '<div id="header_column_2"><strong>'._pi_lang_type.'</strong></div>';		
	
		//loop through items and echo data to hidden fields
		$counter = 0;
		foreach($rows as $row){	
			$areThereItems = true;
			$counter = $counter + 1;			
			$title = $row->title;
			$title = str_replace('"','&quot;',$title);	
			$item_type = $row->itemtype;			
			
			if($this->pi_config['truncate_item_title']){
				$title = $this->truncate_string($title, $this->pi_config['truncate_item_title']);
			}
			
			if($item_type==''){
				$item_type = 'text';
			}
			
			$item_typename = $this->translate_item_type($item_type);
			$no_access = '';
			
			//check if itemtype is installed
			if($item_typename==''){				
				$no_access = _pi_lang_itemtypenotinstalled2;
			}	
			
			//check access for itemtype
			if(!$this->check_useraccess_itemtype($item_type)){				
				$no_access = _pi_lang_noitemtypeaccess;
			}	
			
			//check if itemtype is published
			if(!in_array($item_type,$this->itemtypes)){				
				$no_access = _pi_lang_itemtypenotpublished.' '.$item_type;
			}	
			
			//check item-access
			if(!$this->check_item_access($row->id)){				
				$no_access = _pi_lang_noitemaccess;
			}
			
			//if user is only allowed to edit own items
			if($this->checkUserActionRight(175)!=true){		
				if($this->user_id!=$row->created_by){
					$no_access = _pi_lang_you_are_not_author;
				}
			}
			
			echo '<input name="reorder_item_id_'.$counter.'" id="reorder_item_id_'.$counter.'" type="hidden" value="'.$row->id.'" />';
			
			//column 1					
			echo '<div id="item_column_1_'.$counter.'">';
			if($no_access){				
				echo '<span class="editlinktip" onMouseOver="return overlib(\''.$no_access.'\', CAPTION, \'\', BELOW, RIGHT);" onMouseOut="return nd();" >';
				echo '<img src="components/com_pi_pages_and_items/images/no_access.gif" alt="'.$no_access.'" />';
				echo '</span>&nbsp;';
			}
			echo '<a href="index2.php?option=com_pi_pages_and_items&task=item&sub_task=edit&pageId='.$pageId.'&itemId='.$row->id.'">'.$title.'</a>';
			echo '</div>';			
			
			//column 2					
			echo '<div id="item_column_2_'.$counter.'">';
			echo $item_typename.'</div>';		
						
		}
		echo '</div>';
	
		
		//2 hidden fields which are usefull for updating the ordering when submitted
		echo '<input name="items_are_reordered" id="items_are_reordered" type="hidden" value="false" />';
		echo '<input name="items_total" id="items_total" type="hidden" value="'.$counter.'" />';
		
		echo '<div id="target_items"></div>';
		echo '<script src="components/com_pi_pages_and_items/javascript/reorder_items.js" language="JavaScript" type="text/javascript"></script>';
		echo '<script language="JavaScript"  type="text/javascript">';
		echo "<!--\n";	
		echo "var items_total = ".$counter.";\n";		
		echo "var number_of_columns = '2';\n";
		echo "var ordering = '"._pi_lang_ordering."';\n";
		echo "var no_items = '"._pi_lang_noitemsonthispage."';\n";
		
		//check what sort of item ordering and if not by ordering hide arrows
		$menu_params = explode( "\n", $menu_params);		
		for($n = 0; $n < count($menu_params); $n++){			
			$values_temp = explode('=',$menu_params[$n]); 
			$var = $values_temp[0];			
			$value = str_replace($var.'=','',$menu_params[$n]);
			$value = trim($value);
			$value = htmlspecialchars($value);
			$menu_param[$var] = $value;			 
		}		
		if($menu_param['orderby_pri']!='' || $menu_param['orderby_sec']!='order'){
			echo "var hide_arrows = true;\n";
		}
				
		echo "document.onload = print_items();\n";
		echo "-->\n";
		echo "</script>\n";
		echo '</div>';			
	}
	
	function itemtype_select($menu_id){
		echo _pi_lang_itemtype.': ';
	
		//get itemtype aliasses in new array
		$itemtypes = array();
		foreach($this->itemtypes as $type){	
			$type_array = array($type, $this->translate_item_type($type));
			array_push($itemtypes, $type_array);
		}
		
		//sort array on alias
		foreach ($itemtypes as $key => $row) {
			$order[$key]  = strtolower($row[1]);    
		}
		array_multisort($order, SORT_ASC, $itemtypes);

		echo '<select name="select_itemtype" id="select_itemtype">';
		foreach($itemtypes as $type){			
			if($this->check_useraccess_itemtype($type[0])){
				if($type[1]){//only show if itemtype is installed
					echo '<option value="'.$type[0].'"';
					if($type[0]=='text'){
						echo ' selected="selected"';
					}	
					echo '>'.$type[1];
					if($type[0]=='text'){
						echo ' ('._pi_lang_default.')';
					}
					echo '</option>';
				}
			}				
		}		
		echo '</select>';
		
		echo '<input type="button" value="'._pi_lang_new_item.'" class="button" title="'._pi_lang_make_new_item.'" onclick="new_item('.$menu_id.')" style="background: url(components/com_pi_pages_and_items/images/item.gif) no-repeat #d4d0c8 3px 2px; margin-left: 10px;" />	';
	}			
		
	function reorderItemsCategory($catId) {				
		$this->db->setQuery("SELECT id, ordering, catid FROM #__content WHERE catid='$catId' AND (state='0' OR state='1') ORDER BY ordering ASC"  );
		$rows = $this->db-> loadObjectList();
		
		$counter = 1;
		foreach($rows as $row){	
			//reorder to make sure all is well
			$rowId = $row->id;		
			$this->db->setQuery( "UPDATE #__content SET ordering='$counter' WHERE id='$rowId'"	);
			if (!$this->db->query()) {
				echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
				exit();
			}
			$counter = $counter + 1;	
		}
		return $counter;			
	}
		
	//trash all items on a page (category)	
	function trashItemsCategory($trashCatId){			
		//get content id's which are on frontpage
		$this->db->setQuery("SELECT content_id FROM #__content_frontpage");
		$frontpage_items = $this->db->loadResultArray();
		
		//get content-index to know which item has whichitemtype
		$this->db->setQuery("SELECT item_id, itemtype FROM #__pi_item_index");
		$index_items = $this->db->loadObjectList();
		
		//trash all items in the category
		$this->db->setQuery("SELECT id FROM #__content WHERE catid='$trashCatId'"  );
		$rows = $this->db->loadObjectList();
		foreach($rows as $row){	
			$item_id = $row->id;
			$this->db->setQuery( "UPDATE #__content SET state='-2' WHERE id='$item_id'"	);
			if (!$this->db->query()) {
				echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
				exit();
			}
			
			//if item was on frontpage, take it off
			if(in_array($item_id, $frontpage_items)){
				$this->take_item_off_frontpage($item_id);		
			}	
			
			//if item was plugin, delete sub-item rows etc.			
			foreach($index_items as $index_item){
				if($item_id==$index_item->item_id && $index_item->itemtype!='text' && $index_item->itemtype!='html' && $index_item->itemtype!='other_item'){					
					$this->delete_plugin_items($item_id, $index_item->itemtype);
				}		
			}
			
			//if item had duplicate-items trash those as well
			$this->db->setQuery("SELECT item_id FROM #__pi_item_other_index WHERE other_item_id='$item_id' ");
			$other_items = $this->db->loadObjectList();
			foreach($other_items as $other_item){
				$this->update_duplicate_item($other_item->item_id, $item_id);
			}
			
			//if item was of itemtype other-item disconnect it from original item by deleting the row in the ohter-item-index
			if($index_item->itemtype=='other_item'){
				$this->delete_other_item_entry($item_id);
			}				
		}			
	}	
		
	//trash page and all items on page	
	function trashPage($trashPageId){		
		//check if menuitem is content-category-blog, and if so, get cat_id
		$content_category_blog = false;
		if(defined('_JEXEC')){
			//joomla 1.5
			$this->db->setQuery("SELECT link, type FROM #__menu WHERE id='$trashPageId' LIMIT 1");
			$rows = $this->db->loadObjectList();
			$row = $rows[0];
			if((strstr($row->link, 'index.php?option=com_content&view=category&layout=blog') && $row->type!='url')){
				$content_category_blog = true;
				$cat_id = str_replace('index.php?option=com_content&view=category&layout=blog&id=','',$row->link);
			}
		}else{
			//joomla 1.0.x
			$this->db->setQuery("SELECT type, componentid FROM #__menu WHERE id='$trashPageId' LIMIT 1");
			$rows = $this->db->loadObjectList();
			$row = $rows[0];
			if($row->type=='content_blog_category'){
				$content_category_blog = true;
				$cat_id = $row->componentid;
			}
		}	
		
		//trash mainmenuitem
		$this->db->setQuery( "UPDATE #__menu SET published='-2' WHERE id='$trashPageId'");
		if (!$this->db->query()) {
			echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
			exit();
		}
		
		//only trash items on page when its a content_blog_category
		if($content_category_blog){		
			//trash all items on the page (category)
			$this->trashItemsCategory($cat_id);
		}
		
		//delete category
		$query = "DELETE FROM #__categories WHERE id='$cat_id'"	;
		$this->db->setQuery( $query );
		$this->db->query();
		
		//trash all underlying child-pages
		$this->trashPageChildren($trashPageId);	
		
		//clean item-index
		$this->keep_item_index_clean();		
	}	
		
		
	//trash page and underlying pages and all items on them	
	function trashPageChildren($trashPageId){
		$this->db->setQuery("SELECT id FROM #__menu WHERE parent='$trashPageId'"  );
		$rows = $this->db-> loadObjectList();
	
		foreach($rows as $row){		
			$this->trashPage($row->id);
		}				
	}
	
		
	
	function page_move_save(){
		global $pageId, $pageType;
		
		if(!$this->pi_config['use_user_access_component'] || ($this->pi_config['use_user_access_component'] && $this->checkUserActionRight(7))){
			//user has right to move page	
			
			$old_parent_id = $this->get_var('old_parent_id', '');
			$new_parent_id = $this->get_var('new_parent_id', '');
			$new_menutype = $this->get_var('new_menutype', '', 'post');
			$old_menutype = $this->get_var('old_menutype', '', 'post');						
							
			//reorder menuitems of (new) menutype to make sure moved page is last in order			
			$this->db->setQuery("SELECT id, ordering FROM #__menu WHERE menutype='$new_menutype' AND parent='$new_parent_id' ORDER BY ordering ASC");
			$rows = $this->db-> loadObjectList();
			$counter = 1;
			foreach($rows as $row){	
				$page_id = $row->id;				
				$this->db->setQuery("UPDATE #__menu SET ordering='$counter' WHERE id='$page_id'");
				if (!$this->db->query()) {
					echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
					exit();
				}		
				$counter = $counter+1;	
			}
			
			//get the new parent's-menuitem's sublevel. Only for 1.5.x, in 1.0.x this never seemed to have worked at all.			
			$sublevel = $this->get_sublevel_add_one($new_parent_id);							
			
			//update the menu item of the page to go under new parent
			$this->db->setQuery("UPDATE #__menu SET menutype='$new_menutype', parent='$new_parent_id', sublevel='$sublevel', ordering='$counter' WHERE id='$pageId'");
			if (!$this->db->query()) {
				echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>\n";
				exit();
			}	
			
			//reorder mainmenu to make sure the pages under the old parent are tidied up			
			$this->db->setQuery("SELECT id, ordering FROM #__menu WHERE menutype='$old_menutype' AND parent='$old_parent_id' ORDER BY ordering ASC");
			$rows = $this->db-> loadObjectList();
			$counter = 1;
			foreach($rows as $row){	
				$page_id = $row->id;				
				$this->db->setQuery("UPDATE #__menu SET ordering='$counter' WHERE id='$page_id'");
				if (!$this->db->query()) {
					echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
					exit();
				}		
				$counter = $counter+1;	
			}	
			
			//if item changed menutype, all underlying items should change menutype as well
			if($new_menutype!=$old_menutype){
				$this->change_menutype_check_children($pageId, $new_menutype);
			}			
			
			//update section id only if parent is not root
			if($new_parent_id!=0 && $this->pi_config['inherit_from_parent_move']){
				//get category id of new parent
				foreach($this->menuitems as $row){
					if($row->id==$new_parent_id){
						$componentid = $row->componentid;
						$link = $row->link;
					}
				}
				if( defined('_JEXEC') ){
					//joomla 1.5
					$new_parent_cat_id = str_replace('index.php?option=com_content&view=category&layout=blog&id=','',$link);
				}else{
					//joomla 1.0.x		
					$new_parent_cat_id = $componentid;
				}			
			
				//get section id of new parent
				$this->db->setQuery("SELECT section FROM #__categories WHERE id='$new_parent_cat_id'");
				$rows = $this->db->loadObjectList();
				$row = $rows[0];
				$new_parent_section_id = $row->section;	
				
				//update this page and all underlying pages' categories and items' to get the new section id
				if($new_parent_section_id){
					$this->section_update_page($pageId, $new_parent_section_id);	
				}		
			}
			
			//redirect
			$this->redirect_to_url("index2.php?option=com_pi_pages_and_items&task=page&sub_task=edit&pageId=$pageId", _pi_lang_pagemovesaved);
		
		}else{
			//no rights to move page
			echo '<script> alert(\''._pi_lang_no_move_page.'\'); window.history.go(-1); </script>\n';
			exit();	
		}	
	}
	
	function change_menutype_check_children($page_id, $new_menutype){
		$this->db->setQuery("SELECT id FROM #__menu WHERE parent='$page_id'"  );
		$rows = $this->db-> loadObjectList();
	
		foreach($rows as $row){		
			$this->change_menutype($row->id, $new_menutype);
		}
	}
	
	function change_menutype($page_id, $new_menutype){
		$this->db->setQuery( "UPDATE #__menu SET menutype='$new_menutype' WHERE id='$page_id'");
		if (!$this->db->query()) {
			echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
			exit();
		}
		
		$this->change_menutype_check_children($page_id, $new_menutype);
	}
	
	function item_save(){		
		global $task;		
		
		$new_or_edit = 'edit';		
		
		//in order of db columns
		
		$item_id = $this->get_var('id', '', 'post');
		$item_type = $this->get_var('item_type', '', 'post');
				
		//get item title
		$title = $this->get_var('title', '', 'post');
		if(defined('_JEXEC')){
			//joomla 1.5
			$title = addslashes($title);
		}
		
		//get alias
		$alias = $this->get_var('title_alias', '', 'post');		
		if($alias==''){
			$alias = $this->make_alias($title);
		}else{
			$alias = $this->make_alias($alias);
		}
		if(defined('_JEXEC')){
			//joomla 1.5
			$alias = addslashes($alias);
		}
		
		//make alias unique
		if($this->pi_config['make_article_alias_unique']){
			$alias = $this->make_alias_unique($alias, 'content', $item_id);
		}		
		
		//get text, split if joomla 1.5
		if(defined('_JEXEC')){
			//joomla 1.5			
			if(JRequest::getVar('text','','post','string', JREQUEST_ALLOWRAW)){
				//text item or itemtype plugin which uses the joomla 1.5 editor name='text'									
				$text = JRequest::getVar('text','','post','string', JREQUEST_ALLOWRAW );				
				$text = str_replace('<br>','<br />', $text);		
				$length = strlen($text);
				$pos = strpos($text, '<hr id="system-readmore" />');
				$pos_no_start = strpos($text, 'hr id="system-readmore" />');				
				if($pos){
					$pos2 = $pos + 27;		
					$introtext = addslashes(substr($text, 0, $pos));
					$fulltext = addslashes(substr($text, $pos2, $length));	
				}else{
					$introtext = addslashes($text);
					$fulltext = '';
				}
				if($pos_no_start && !$pos){
					//there is no code in fromt of the hr							
					$introtext = '';
					$pos_no_start2 = 26;
					$text = str_replace('<hr id="system-readmore" />','',$text);	
					$fulltext = addslashes($text);	
				}
			}else{
				//HTML-item or itemtype plugin which uses joomla 1.0.x-style editor name='introtext'
				$introtext = addslashes(JRequest::getVar('introtext','','post','string', JREQUEST_ALLOWRAW));				
				$introtext = str_replace('<br>','<br />', $introtext);
				$fulltext = addslashes(JRequest::getVar('fulltext','','post','string', JREQUEST_ALLOWRAW));				
				$fulltext = str_replace('<br>','<br />', $fulltext);				
			}					
		}else{
			//joomla 1.0.x					
			$introtext = mosGetParam( $_POST, 'introtext','', _MOS_ALLOWRAW);
			$fulltext = mosGetParam( $_POST, 'fulltext','', _MOS_ALLOWRAW);				
		}		

		//state
		$state = intval($this->get_var('state'));
		
		//if user has no rights to publish set to not published
		if($this->checkUserActionRight(12)!=true){
			$state = 0;			
		}
			
		//if trash check for right and trash
		$trash_item = intval($this->get_var('trash_item'));	
		if($trash_item==1){		
			if($this->checkUserActionRight(13)!=true){
				echo '<script> alert(\''.addslashes(_pi_lang_no_item_trash).'\'); window.history.go(-1); </script>';
				exit();	
			}else{							
				$this->delete_plugin_items($item_id, $item_type);
				//$this->delete_plugin_items($item_id, $item_type);
				$state = -2;	
			}
		}	
		
		//category id
		$cat_id = intval($this->get_var('cat_id'));	
		
		//get menu_id
		if($this->get_var('edit_from_frontend', '', 'post')){
			//frontend
			if(!$item_id){				
				$pageId = $this->get_menu_id_from_category_blog($cat_id);				
			}else{
				$pageId = $this->get_var('page_id', '', 'post');				
			}									
		}else{
			//backend
			$pageId = $this->get_var('page_id', '', 'post');
		}		
		
		//section id
		$section_id = intval($this->get_var('section_id'));	
		
		//if joomla 1.5 get date-manipulation-utilities
		if( defined('_JEXEC') ){
			//joomla 1.5		
			$config =& JFactory::getConfig();
			$tzoffset = $config->getValue('config.offset');
			jimport('joomla.utilities.date');		
		}
		
		$created = trim($this->get_var('created'));	
		if($created==_pi_lang_now || $created==''){			
			$created = $this->get_date_now(true);				
		}else{	
			if(defined('_JEXEC') ){
				//joomla 1.5
				//add empty time if only date was entered
				if ($created && strlen(trim($created)) <= 10){
					$created .= ' 00:00:00';
				}
			}			
		}			
		$created = $this->get_date_ready_for_database($created);
		
		
		$created_by = $this->get_var('created_by');
		$created_by_alias = $this->get_var('created_by_alias');
		
		$modified = $this->get_date_now(true);	
		$modified = $this->get_date_ready_for_database($modified);		
		
		$modified_by = intval( $this->get_var('modified_by') );
		$publish_up = trim($this->get_var('publish_up'));	
		if($publish_up==_pi_lang_now || $publish_up==''){
			$publish_up = $this->get_date_now(true);
		}else{	
			if( defined('_JEXEC') ){
				//joomla 1.5
				//add empty time if only date was entered
				if ($publish_up && strlen(trim($publish_up)) <= 10){
					$publish_up .= ' 00:00:00';
				}				
			}			
		}
		$publish_up = $this->get_date_ready_for_database($publish_up);				
				
		$publish_down = trim($this->get_var('publish_down'));			
		if($publish_down==_pi_lang_never || $publish_down==''){
			if( defined('_JEXEC') ){
				//joomla 1.5
				$db	= & JFactory::getDBO();
				$null_date = $db->getNullDate();
				$publish_down = $null_date;					
			}else{
				//joomla 1.0.x
				$publish_down = '0000-00-00 00:00:00';
			}		
		}else{
			if( defined('_JEXEC') ){
				//joomla 1.5
				//add empty time if only date was entered
				if ($publish_down && strlen(trim($publish_down)) <= 10){
					$publish_down .= ' 00:00:00';
				}					
			}
			$publish_down = $this->get_date_ready_for_database($publish_down);
		}		
			
	
		$itemAttribs = $this->get_var('itemAttribs', '');
		$attribs = '';		
		for($n = 0; $n < count($itemAttribs); $n++){
			$row = each($itemAttribs);
			$attribs = $attribs."$row[key]=$row[value]\n";	
		}	
		
		$version = intval($this->get_var('version'));
		$metakey = addslashes($this->get_var('metakey', ''));
		$metadesc = addslashes($this->get_var('metadesc', ''));
		$access = intval($this->get_var('access', ''));
		
		//metadata only for joomla 1.5
		if(defined('_JEXEC')){

			//joomla 1.5
			$metadata = $this->get_var('metadata', '');
			$metadata_stuff = '';
			for($n = 0; $n < count($metadata); $n++){
				$row = each($metadata);
				$metadata_stuff = $metadata_stuff."$row[key]=$row[value]\n";	
			}
		}
		
		$show_title_item = intval($this->get_var('show_title_item'));	
		$item_on_frontpage = intval($this->get_var('frontpage'));			
		
		//switch new - edit item	
		if(!$item_id){
			//begin new item		
				
			$new_or_edit = 'new';
			
			//reorder items of this category and get new number for ordering
			$ordering = $this->reorderItemsCategory($cat_id);		
			
			//insert new item
			if( defined('_JEXEC') ){
	
				//joomla 1.5
				$this->db->setQuery( "INSERT INTO #__content SET title='$title', alias='$alias', introtext='$introtext', `fulltext`='$fulltext', state='$state', sectionid='$section_id', catid='$cat_id', created='$created', created_by='$created_by', modified='$modified', created_by_alias='$created_by_alias', publish_up='$publish_up', publish_down='$publish_down', attribs='$attribs', version='$version', ordering='$ordering', metakey='$metakey', metadesc='$metadesc', access='$access', metadata='$metadata_stuff' ");
			}else{
				//joomla 1.0.x	
						
				$this->db->setQuery( "INSERT INTO #__content SET title='$title', title_alias='$title', introtext='$introtext', `fulltext`='$fulltext', state='$state', sectionid='$section_id', catid='$cat_id', created='$created', created_by='$created_by', modified='$modified', created_by_alias='$created_by_alias', publish_up='$publish_up', publish_down='$publish_down', attribs='$attribs', version='$version', ordering='$ordering', metakey='$metakey', metadesc='$metadesc', access='$access' ");	
			}		
			
			if (!$this->db->query()) {
				echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
				exit();
			}
			
			//get insert id
			$item_id = $this->db->insertid();
			
			//insert new index item			
			$this->db->setQuery( "INSERT INTO #__pi_item_index SET item_id='$item_id', itemtype='$item_type', show_title='$show_title_item'");			
			if (!$this->db->query()) {
				echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
				exit();
			}
			
			//if customitemtype save fields
			if(strpos($item_type, 'ustom_')){			
				$this->save_custom_itemtype($item_type, $trash_item, $item_id);						
			}	
			
			//if other item do insert
			if($item_type=='other_item'){				
				//get other_item_id
				//get vars
				if( defined('_JEXEC') ){
					//joomla 1.5
					$other_item_id = JRequest::getVar('other_item_id', '');				
				}else{
					//joomla 1.0.x
					$other_item_id = mosGetParam( $_REQUEST, 'other_item_id', '' );				
				}
				$this->db->setQuery( "INSERT INTO #__pi_item_other_index SET item_id='$item_id', other_item_id='$other_item_id'");			
				if (!$this->db->query()) {
					echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
					exit();
				}
				//update other item
				$this->update_duplicate_item($item_id, $other_item_id);			
			}					
			
			//item on frontpage								
			if($item_on_frontpage==1){
				$this->put_item_on_frontpage($item_id);
			}		
			
			//send new-item-notification if configed to do so
			if(!$this->checkUserActionRight(15) && $this->user_type!='Super Administrator'){
				$subject = _pi_lang_notify_new_item_1;				
				$message = _pi_lang_notify_hello.",\n\n";
				$message .= _pi_lang_notify_new_item_2.":\n";
				$message .= $this->live_site."\n\n";
				$message .= _pi_lang_notify_new_item_by.":\n";				
				$message .= $this->get_username()."\n\n";
				$message .= _pi_lang_notify_item_1."\n";
				if(defined('_JEXEC')){
					//joomla 1.5					
					//$url = 'index.php?option=com_content&view=category&layout=blog&id='.$cat_id.'&Itemid='.$pageId;	
					$url = 'index.php?option=com_content&view=article&id='.$item_id.'&Itemid='.$pageId;					
				}else{
					//joomla 1.0.x
					$url = 'index.php?option=com_content&task=blogcategory&id='.$cat_id.'&Itemid='.$pageId;
				}
				$message .= $this->live_site.$url."\n\n";				
				$message .= _pi_lang_notify_item_3.":\n";
				$message .= $title."\n\n";	
				$message .= _pi_lang_notify_link_pi.":\n";				
				$message .= $this->live_site.'administrator/index2.php?option=com_pi_pages_and_items&task=item&sub_task=edit&pageId='.$pageId.'&itemId='.$item_id."\n\n";						
				$this->send_notification($subject, $message);
			}
			
			//set item-access rights if using Admin-User-Access
			if($this->pi_config['use_user_access_component'] && $this->user_access_config['active_items'] && $this->user_access_config['item_inherits_access']!='no_default_has_no_access'){
				$this->class_ua->set_new_item_access_for_groups($item_id, $pageId, $section_id);			
			}
			
			//end new item
		}else{
			//begin edit item			
			
			//update item
			if( defined('_JEXEC') ){
				//joomla 1.5			
				$this->db->setQuery( "UPDATE #__content SET title='$title', alias='$alias', introtext='$introtext', `fulltext`='$fulltext', state='$state', sectionid='$section_id', catid='$cat_id', created='$created', created_by='$created_by', modified='$modified', modified_by='$modified_by', created_by_alias='$created_by_alias', publish_up='$publish_up', publish_down='$publish_down', attribs='$attribs', version='$version', metakey='$metakey', metadesc='$metadesc', access='$access', metadata='$metadata_stuff' WHERE id='$item_id' ");
			}else{
				//joomla 1.0.x			
				$this->db->setQuery( "UPDATE #__content SET title='$title', title_alias='$title', introtext='$introtext', `fulltext`='$fulltext', state='$state', sectionid='$section_id', catid='$cat_id', created='$created', created_by='$created_by', modified='$modified', modified_by='$modified_by', created_by_alias='$created_by_alias', publish_up='$publish_up', publish_down='$publish_down', attribs='$attribs', version='$version', metakey='$metakey', metadesc='$metadesc', access='$access'  WHERE id='$item_id' ");	
			}		
			if (!$this->db->query()) {
				echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
				exit();
			}			
			
			//check if item has a entry in item-index (if so, its been created or editted with PI before) if not, make a new index row
			$this->db->setQuery("SELECT id FROM #__pi_item_index WHERE item_id='$item_id' LIMIT 1");
			$rows = $this->db->loadObjectList();
			$row = $rows[0];
			$id = $row->id;
			if(!$id){
				$this->db->setQuery( "INSERT INTO #__pi_item_index SET item_id='$item_id', itemtype='$item_type', show_title='$show_title_item'");			
				if (!$this->db->query()) {
					echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
					exit();
				}
			}else{
				$this->db->setQuery( "UPDATE #__pi_item_index SET itemtype='$item_type', show_title='$show_title_item' WHERE id='$id' ");			
				$this->db->query();
			}										
			
			//if other_item update
			if($item_type=='other_item'){				
				//get other_item_id				
				if( defined('_JEXEC') ){
					//joomla 1.5
					$other_item_id = JRequest::getVar('other_item_id', '');				
				}else{
					//joomla 1.0.x
					$other_item_id = mosGetParam( $_REQUEST, 'other_item_id', '' );				
				}
				$this->db->setQuery( "UPDATE #__pi_item_other_index SET other_item_id='$other_item_id' WHERE item_id='$item_id'");			
				if (!$this->db->query()) {
					echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
					exit();
				}
				//update other item
				$this->update_duplicate_item($item_id, $other_item_id);	
				
				//update index item	for visiblitity title	
				$this->db->setQuery( "UPDATE #__pi_item_index SET show_title='$show_title_item' WHERE item_id='$item_id'");			
				if (!$this->db->query()) {
					echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
					exit();
				}	
				
				//update item state	(because it just got overwritten above in update_duplicate_item()
				$this->db->setQuery( "UPDATE #__content SET state='$state' WHERE id='$item_id'");			
				if (!$this->db->query()) {
					echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
					exit();
				}
				
				//if other-item delete also take out row in other item index
				if($state=='-2'){
					$this->delete_other_item_entry($item_id);
				}		
			}			
			
			//if customitemtype save fields
			if(strpos($item_type, 'ustom_')){														
				$this->save_custom_itemtype($item_type, $trash_item, $item_id);						
			}		
			
			//check if the saved item has other_items linked to it, if so, update those			
			$this->update_other_items_if_needed($item_id);		
			
			//item on frontpage
			$this->db->setQuery("SELECT content_id FROM #__content_frontpage WHERE content_id='$item_id' LIMIT 1");
			$rows_frontpage = $this->db->loadObjectList();
			$is_on_frontpage = false;
			foreach($rows_frontpage as $row_frontpage){
				$is_on_frontpage = $row_frontpage->content_id;
			}		
			if($is_on_frontpage){
				if($item_on_frontpage==0 || $trash_item){
					$this->take_item_off_frontpage($item_id);
				}			
			}else{
				if($item_on_frontpage==1 && !$trash_item){
					$this->put_item_on_frontpage($item_id);
				}
			}		
			
			//send edit-item-notification if configed to do so
			if(!$this->checkUserActionRight(16)  && $this->user_type!='Super Administrator'){
				$subject = _pi_lang_notify_edit_item_1;
				$message = _pi_lang_notify_hello.",\n\n";
				$message .= _pi_lang_notify_edit_item_2.":\n";
				$message .= $this->live_site."\n\n";
				$message .= _pi_lang_notify_item_editted_by.":\n";				
				$message .= $this->get_username()."\n\n";
				$message .= _pi_lang_notify_item_1."\n";
				if(defined('_JEXEC')){
					//joomla 1.5
					//$url = 'index.php?option=com_content&view=category&layout=blog&id='.$cat_id.'&Itemid='.$pageId;	
					$url = 'index.php?option=com_content&view=article&id='.$item_id.'&Itemid='.$pageId;					
				}else{
					//joomla 1.0.x
					$url = 'index.php?option=com_content&task=blogcategory&id='.$cat_id.'&Itemid='.$pageId;
				}
				$message .= $this->live_site.$url."\n\n";				
				$message .= _pi_lang_notify_item_3.":\n";
				$message .= $title."\n\n";			
				$this->send_notification($subject, $message);
			}
			
			//end edit item
		}	
		
		//save itemtype plugin-specific things		
		if(file_exists(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/itemtypes/'.$item_type.'/'.$item_type.'.php') && $state!= -2){
			require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/itemtypes/'.$item_type.'/'.$item_type.'.php');
						
			$class_name = 'class_itemtype_'.$item_type;		
			$class_itemtype = new $class_name();		
			if(method_exists($class_itemtype,'item_save')){							
				$class_itemtype->item_save($item_id);
			}	
		}
		
		/*
		//call onBeforeContentSave-event to work with add-keywords-plugin
		//I know this should actually be loaded before the content is saved, but then the output of the
		//custom item types would be ignored
		//so here is a sort of workaround
		$this->pi_config['use_addkeyswordsplugin'] = 1;//this will be included in the config if this is included in a future version
		if($this->pi_config['use_addkeyswordsplugin']){
			$row = & JTable::getInstance('content');
			$row->id = $item_id;
			$row->title = $title;		
			
			//get the actual output
			$this->db->setQuery("SELECT introtext, `fulltext` "
			."FROM #__content "
			."WHERE id='$item_id' "
			."LIMIT 1 "
			);
			$rows_items = $this->db->loadObjectList();
			foreach($rows_items as $row_item){	
				$row->introtext = $row_item->introtext;
				$row->fulltext = $row_item->fulltext;
			}	
			
			$row->sectionid = $section_id;
			$row->catid = $cat_id;
			$row->metakey = $metakey;
			$row->metadesc = $metadesc;
			$isNew = 0;
			if($new_or_edit = 'new'){
				$isNew = 1;
			}
			$dispatcher = & JDispatcher::getInstance();
			$result = $dispatcher->trigger('onBeforeContentSave', array(&$row, $isNew));
			$metakey = $row->metakey;
			$metadesc = $row->metadesc;
			
			$this->db->setQuery( "UPDATE #__content SET metakey='$metakey', metadesc='$metadesc' WHERE id='$item_id' ");
			$this->db->query();
		}
		*/
		
		
		//do Acesef SEF url stuff
		$acesef_url_id = $this->get_var('acesef_url_id', '', 'int');
		$page_id = $this->get_var('page_id', '', 'int');
		$this->acesef_item($acesef_url_id, $page_id, $cat_id, $item_id, $title, $metadesc, $metakey, $alias);	
		
		//sanitize item-index-table
		$this->keep_item_index_clean();
		
		//clean cache
		$this->clean_cache_content();		
		
		//redirect
		if($this->get_var('edit_from_frontend', '', 'post')){
			//frontend
			if($new_or_edit=='new'){				
				$page_id = $this->get_menu_id_from_category_blog($cat_id);				
			}else{
				$page_id = $this->get_var('page_id', '', 'post');				
			}
			if($this->pi_config['item_save_redirect']=='category_blog'){
				//redirect to categroy blog					
				if($page_id){
					$url = $this->get_url_from_menuitem($page_id);
				}else{
					$url = 'index.php';
				}	
			}elseif($this->pi_config['item_save_redirect']=='url'){
				//redirect to custom url
				$url = $this->pi_config['item_save_redirect_url'];
			}else{
				//redirect to item in full view
				$url = 'index.php?option=com_content&amp;view=article&amp;id='.$item_id.'&amp;catid='.$cat_id.'&amp;Itemid='.$page_id;
			}				
		}else{
			//backend
			$url = 'index2.php?option=com_pi_pages_and_items&task=page&sub_task=edit&pageId='.$pageId;
		}
		$mesage = _pi_lang_item_saved;
		if($state==-2){
			$mesage = _pi_lang_item_trashed;
		}
		$apply = $this->get_var('item_apply', '', 'post');	
		if($apply){
			$url = 'index2.php?option=com_pi_pages_and_items&task=item&sub_task=edit&pageId='.$pageId.'&itemId='.$item_id;
		}	
		$this->redirect_to_url( $url, $mesage);	
	}
	
	function delete_other_item_entry($item_id){		
		$this->db->setQuery("DELETE FROM #__pi_item_other_index WHERE item_id='$item_id'");
		$this->db->query();
	}
	
	function get_menu_id_from_category_blog($cat_id){
		//get page data
		$this->db->setQuery("SELECT id, link, componentid, type FROM #__menu ");
		$all_menuitems = $this->db->loadObjectList();	
		
		//make a new array from all categories which are used as category-blog-pages in menu
		foreach($all_menuitems as $menuitem){
			if(((strstr($menuitem->link, 'com_content&view=category&layout=blog') && $menuitem->type=='url') || !strstr($menuitem->link, 'com_content&view=category&layout=blog')) && $menuitem->type!='content_blog_category'){
				//something else
			}else{
				//category-blog-page
				if(defined('_JEXEC')){
					//joomla 1.5
					$cat_id_row = str_replace('index.php?option=com_content&view=category&layout=blog&id=','',$menuitem->link);				
				}else{	
					//joomla 1.0.x
					$cat_id_row = $menuitem->componentid;				
				}
				if($cat_id_row==$cat_id){
					$menu_id = $menuitem->id;
					break;
				}											
			}			
		}
		return $menu_id;			
	}
	
	function get_url_from_menuitem($menu_id){
		$this->db->setQuery("SELECT link FROM #__menu WHERE id='$menu_id' LIMIT 1");
		$menu_items = $this->db->loadResultArray();	
		$menu_url = $menu_items[0].'&Itemid='.$menu_id;				
		return $menu_url;
	}
	
	function update_other_items_if_needed($item_id){
		$this->db->setQuery("SELECT item_id FROM #__pi_item_other_index WHERE other_item_id='$item_id' ");
		$other_items = $this->db->loadObjectList();
		foreach($other_items as $other_item){
			$this->update_duplicate_item($other_item->item_id, $item_id);
		}	
	}	
	
	function save_custom_itemtype($item_type, $trash_item, $item_id){	
		$pos = strpos($item_type, 'ustom_');
		$type_id = substr($item_type, $pos+6, strlen($item_type));
					
		//get fields
		$this->db->setQuery( "SELECT id, plugin, params "
		. "\nFROM #__pi_custom_fields "
		. "\nWHERE type_id='$type_id' "
		);
		$fields = $this->db->loadObjectList();
		
		if($trash_item==1){	
						
			//ADD MS
			//if field-class got a special function for DELET item do that	
			foreach($fields as $field)
			{
				if($this->check_field_class_function($field->plugin,'extended_save_custom_itemtype_delete_item'))
				{
					if(in_array($field->plugin, $this->fieldtypes_integrated))
					{
						require_once(dirname(__FILE__).'/class_custom_item_types.php');
						$class_name = 'class_fieldtype_'.$field->plugin;
						$class_object = new $class_name();
						$class_object->extended_save_custom_itemtype_delete_item($item_id,$type_id);
						//$class_object->item_delete($item_id, $type_id, $field);
					}
					else
					{
						require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field->plugin.'/'.$field->plugin.'.php');
						$class_name = 'class_fieldtype_'.$field->plugin;
						$class_object = new $class_name();
						$class_object->extended_save_custom_itemtype_delete_item($item_id,$type_id);
						//$class_object->item_delete($item_id, $type_id, $field);
					}
				}
				
				//check if the fieldtype has a function for when the item is deleted, if so, do the function
				if(in_array($field->plugin, $this->fieldtypes_integrated)){
					require_once(dirname(__FILE__).'/class_custom_item_types.php');
					$class_name = 'class_fieldtype_'.$field->plugin;
					$class_object = new $class_name();						
					if(method_exists($class_object, 'item_delete')){												
						$class_object->item_delete($item_id, $type_id, $field);
					}
				}else{
					require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field->plugin.'/'.$field->plugin.'.php');
					$class_name = 'class_fieldtype_'.$field->plugin;
					$class_object = new $class_name();	
					if(method_exists($class_object, 'item_delete')){								
						$class_object->item_delete($item_id, $type_id, $field);
					}
				}
				
			}
			//ADD MS END						
			
			//delete custom field values
			$this->db->setQuery("DELETE FROM #__pi_custom_fields_values WHERE item_id='$item_id'");
			$this->db->query();	
		}else{ 
			//save custom itemtype 
			//get fields 
			//change MS 01.09.2009 
			$this->db->setQuery( "SELECT * "
			."\nFROM #__pi_custom_fields "
			."\nWHERE type_id='$type_id' "																							
			);
			$fields = $this->db->loadObjectList();
			
			//get data-fields
			$this->db->setQuery( "SELECT id, field_id "														
			. "\nFROM #__pi_custom_fields_values "									
			. "\nWHERE item_id='$item_id' "																								
			);
			$data_fields = $this->db->loadObjectList();					
			
			//make array of fields which have a data field and make fields-datafields array	
			$new_cit = true;						
			$fields_datafields_array = array();
			foreach($fields as $field){	
				foreach($data_fields as $field_data){
					if($field_data->field_id==$field->id){							
						$fields_datafields_array[$field_data->field_id] = $field_data->id;
						$new_cit = false;							
						break;
					}						
				}
			}			
			
			foreach($fields as $field){			
				
				$field_id = $field->id;	
				
				$field->item_id = $item_id;				
					
				//if(!$fields_datafields_array[$field_id]){
				if($new_cit){
					//start insert
											
					//if field-class got a special function for saving do that	
					if($this->check_field_class_save_function($field->plugin)){
						if(in_array($field->plugin, $this->fieldtypes_integrated)){
							require_once(dirname(__FILE__).'/class_custom_item_types.php');
							$class_name = 'class_fieldtype_'.$field->plugin;
							$class_object = new $class_name();
							$value = $class_object->field_save($field, 'insert');
						}else{
							require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field->plugin.'/'.$field->plugin.'.php');
							$class_name = 'class_fieldtype_'.$field->plugin;							
							$class_name = new $class_name();												
							$value = $class_name->field_save($field, 'insert');
						}					
					}else{
						//get all values from this field and make into a string	
						//$field_values_array = 'field_values_'.$field_id.'_new';	
						$field_values_array = 'field_values_'.$field_id;					
						$field_values = $this->get_var($field_values_array, false);										
						if(count($field_values)==1){					
							$temp = trim(addslashes($field_values[0]));
							$value = str_replace('"','&quot;',$temp);
						}else{
							$value = '';					
							for($n = 0; $n < count($field_values); $n++){					
								$row = each($field_values);						
								$temp = addslashes("$row[key]-=-$row[value][;-)# ]");					
								$value .= str_replace('"','&quot;',$temp);									
							}
						}						
					}
					
					//do insert
					$this->db->setQuery( "INSERT INTO #__pi_custom_fields_values SET field_id='$field_id', item_id='$item_id', value='$value' ");			
					$this->db->query();
					
					//end insert										
				}else{
					//start update	
					
					$value_id = $fields_datafields_array[$field_id];
					
					//if field plugin got a class for saving, do that
					if($this->check_field_class_save_function($field->plugin)){
						if(in_array($field->plugin, $this->fieldtypes_integrated)){
							require_once(dirname(__FILE__).'/class_custom_item_types.php');
							$class_name = 'class_fieldtype_'.$field->plugin;
							$class_object = new $class_name();
							$value = $class_object->field_save($field, 'update');
						}else{
							require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field->plugin.'/'.$field->plugin.'.php');
							$class_name = 'class_fieldtype_'.$field->plugin;							
							$class_name = new $class_name();												
							$value = $class_name->field_save($field, 'update');
						}											
					}else{
						//get all values from this field and make into a string	
						$field_values_array = 'field_values_'.$field_id;												
						$field_values = $this->get_var($field_values_array, false);															
						if(count($field_values)==1){					
							$temp = trim(addslashes($field_values[0]));
							$value = str_replace('"','&quot;',$temp);
						}else{
							$value = '';					
							for($n = 0; $n < count($field_values); $n++){					
								$row = each($field_values);										
								$temp = addslashes("$row[key]-=-$row[value][;-)# ]");					
								$value .= str_replace('"','&quot;',$temp);										
							}
						}							
					}					
					
					//do update
					$this->db->setQuery( "UPDATE #__pi_custom_fields_values SET value='$value' WHERE id='$value_id' ");			
					$this->db->query();	
					
					//end update
				}						
						
			}//end field loop				
			
			$this->update_content_table_from_custom_itemtype($item_id, $item_type,$new_cit);
			//ADD MS
			foreach($fields as $field)
			{
				$field_id = $field->id;
				//if(!$fields_datafields_array[$field_id])
				if(!isset($fields_datafields_array[$field_id]))
				{
					//start insert
					//if field-class got a special special function for saving do that	
					if($this->check_field_class_function($field->plugin,'extended_save_custom_itemtype_field_save'))
					{
						if(in_array($field->plugin, $this->fieldtypes_integrated))
						{
							require_once(dirname(__FILE__).'/class_custom_item_types.php');
							$class_name = 'class_fieldtype_'.$field->plugin;
							$class_object = new $class_name();
							$class_object->extended_save_custom_itemtype_field_save($field, 'insert',$item_id,$type_id,$fields);
						}
						else
						{
							require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field->plugin.'/'.$field->plugin.'.php');
							$class_name = 'class_fieldtype_'.$field->plugin;
							$class_object = new $class_name();
							$class_object->extended_save_custom_itemtype_field_save($field, 'insert',$item_id,$type_id,$fields);
						}
					}
				}
				//CHANGE MS 19.09.2009
				/*
				else
				{
					//start update	
					//if field-class got a special special function for saving do that	
					if($this->check_field_class_function($field->plugin,'extended_save_custom_itemtype_field_save'))
					{
						if(in_array($field->plugin, $this->fieldtypes_integrated))
						{
							require_once(dirname(__FILE__).'/class_custom_item_types.php');
							$class_name = 'class_fieldtype_'.$field->plugin;
							$class_object = new $class_name();
							$class_object->extended_save_custom_itemtype_field_save($field, 'update',$item_id,$type_id,$fields);
						}
						else
						{
							require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field->plugin.'/'.$field->plugin.'.php');
							$class_name = 'class_fieldtype_'.$field->plugin;
							$class_object = new $class_name();
							$class_object->extended_save_custom_itemtype_field_save($field, 'update',$item_id,$type_id,$fields);
						}
					}
				}
				*/
				//CHANGE MS 19.09.2009 END
			}
			//end field loop MS
			//END ADD MS			
		}//end not item trash
	}
	
	//ADD MS
	function check_field_class_function($field_type, $field_method)
	{
		//if field plugin got a class for somthing special, do that
		$field_class_function_check = 0;
		if(in_array($field_type, $this->fieldtypes_integrated))
		{
			require_once(dirname(__FILE__).'/class_custom_item_types.php');
			$class_name = 'class_fieldtype_'.$field_type;
			$class_object = new $class_name();
			if(method_exists($class_object, $field_method))
			{
				$field_class_function_check = 1;
			}
		}
		elseif(file_exists(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field_type.'/'.$field_type.'.php'))
		{
			require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field_type.'/'.$field_type.'.php');
			$class_name = 'class_fieldtype_'.$field_type;
			$class_object = new $class_name();
			if(method_exists($class_object, $field_method))
			{
				$field_class_function_check = 1;
			}
		}
		return $field_class_function_check;
	}
	//ADD MS END
	
	
	//ADD MS 08.09.2009
	function get_plugin_params_base($field_plugin)
	{
		
		if(in_array($field_plugin, $this->fieldtypes_integrated))
		{
			if(file_exists(dirname(__FILE__).'/class_custom_item_types.php'))
			{
				require_once(dirname(__FILE__).'/class_custom_item_types.php');
				$class_name = 'class_fieldtype_'.$field_plugin;
				$class_plugin = new $class_name();
				if(method_exists($class_plugin, 'params_base'))
				{
					$params = $class_plugin->params_base();
				}
			}
		}
		else
		{
			if(file_exists(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field_plugin.'/'.$field_plugin.'.php'))
			{
				require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field_plugin.'/'.$field_plugin.'.php');
				$class_name = 'class_fieldtype_'.$field_plugin;
				$class_plugin = new $class_name();
				if(method_exists($class_plugin, 'params_base'))
				{
					$params = $class_plugin->params_base();
				}
			}
		}
		if(isset($params))
		{
			$params = implode("\n", $params);
			return $params;
		}
		else
		{
			return false;
		}
	}
	//ADD MS END 08.09.2009
	
	
	function check_field_class_save_function($field_type){
		//if field plugin got a class for saving, do that
		$field_class_save_function = 0;					
		if(in_array($field_type, $this->fieldtypes_integrated)){
			require_once(dirname(__FILE__).'/class_custom_item_types.php');
			$class_name = 'class_fieldtype_'.$field_type;
			$class_object = new $class_name();
			if(method_exists($class_object, 'field_save')){
				$field_class_save_function = 1;	
			}
		}elseif(file_exists(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field_type.'/'.$field_type.'.php')){
			require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field_type.'/'.$field_type.'.php');
			$class_name = 'class_fieldtype_'.$field_type;
			$class_object = new $class_name();
			if(method_exists($class_object, 'field_save')){
				$field_class_save_function = 1;	
			}						
		}		
		return $field_class_save_function;
	}
	
	function update_duplicate_item($item_id, $other_item_id){
		//get the content and title of the original item
		$this->db->setQuery("SELECT * FROM #__content WHERE id='$other_item_id' LIMIT 1");
		$other_items = $this->db->loadObjectList();
		$other_item = $other_items[0];
		$other_item_title = addslashes($other_item->title);
		$other_item_introtext = addslashes($other_item->introtext);
		$other_item_fulltext = addslashes($other_item->fulltext);
		$other_item_state = $other_item->state;
		$other_item_created = $other_item->created;
		$other_item_created_by = $other_item->created_by;
		$other_item_modified = $other_item->modified;
		$other_item_modified_by = $other_item->modified_by;	
		$other_item_publish_up = $other_item->publish_up;
		$other_item_publish_down = $other_item->publish_down;	
		$other_item_attribs = $other_item->attribs;	
		$other_item_access = $other_item->access;	
		$other_item_metakey = $other_item->metakey;
		$other_item_metadesc = $other_item->metadesc;
		$other_item_metadata = $other_item->metadata;
		
		//update the other item
		if(defined('_JEXEC')){
			//joomla 1.5
			$this->db->setQuery( "UPDATE #__content SET title='$other_item_title', introtext='$other_item_introtext', `fulltext`='$other_item_fulltext', state='$other_item_state', created='$other_item_created', created_by='$other_item_created_by', modified='$other_item_modified', modified_by='$modified_by', publish_up='$other_item_publish_up', publish_down='$other_item_publish_down', attribs='$other_item_attribs', access='$other_item_access', metakey='$other_item_metakey', metadesc='$other_item_metadesc', metadata='$other_item_metadata' WHERE id='$item_id'");		
		}else{
			//joomla 1.0.x
			$this->db->setQuery( "UPDATE #__content SET title='$other_item_title', introtext='$other_item_introtext', `fulltext`='$other_item_fulltext', state='$other_item_state', created='$other_item_created', created_by='$other_item_created_by', modified='$other_item_modified', modified_by='$modified_by', publish_up='$other_item_publish_up', publish_down='$other_item_publish_down', attribs='$other_item_attribs', access='$other_item_access', metakey='$other_item_metakey', metadesc='$other_item_metadesc' WHERE id='$item_id'");		
		}				
		if (!$this->db->query()) {
			echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
			exit();
		}
	}
	
	function put_item_on_frontpage($item_id){
		//first get the current order		
		$this->db->setQuery("SELECT content_id, ordering FROM #__content_frontpage ORDER BY ordering ASC");
		$rows = $this->db-> loadObjectList();
		$counter = 1;
		foreach($rows as $row){	
			//reorder to make sure all is well
			$rowContentId = $row->content_id;
			$this->db->setQuery( "UPDATE #__content_frontpage SET ordering='$counter' WHERE content_id='$rowContentId'"	);
			if (!$this->db->query()) {
				echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
				exit();
			}			
			$counter = $counter + 1;				
		}
		//do the insert
		$this->db->setQuery( "INSERT INTO #__content_frontpage SET content_id='$item_id', ordering='$counter'");
		if (!$this->db->query()) {
			echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>\n";
			exit();
		}
	}
	
	function take_item_off_frontpage($item_id){
		$this->db->setQuery("DELETE FROM #__content_frontpage WHERE content_id='$item_id'");
		if (!$this->db->query()) {
			echo "<script> alert('"
			.$this->db-> getErrorMsg()
			."'); window.history.go(-1); </script>";
		}
	}
	
	function item_move_save(){
		$item_id = $this->get_var('item_id', '', 'post');
		$new_parent_id = $this->get_var('new_parent_id');
		$old_cat_id = $this->get_var('old_cat_id');
		
		//find category corresponding to page from where item is moving towards
		foreach($this->menuitems as $row){
			if($row->id==$new_parent_id){
				$componentid = $row->componentid;
				$link = $row->link;
			}
		}
		if( defined('_JEXEC') ){
			//joomla 1.5
			$new_cat_id = str_replace('index.php?option=com_content&view=category&layout=blog&id=','',$link);
		}else{
			//joomla 1.0.x		
			$new_cat_id = $componentid;
		}
		
		//get the section which the category belongs to	
		$this->db->setQuery("SELECT section FROM #__categories WHERE id='$new_cat_id'");
		$rows = $this->db->loadObjectList();
		$row = $rows[0];
		$section_id = $row->section;		
		
		//reorder new category to make sure moved item ends up last
		$new_order = $this->reorderItemsCategory($new_cat_id);
		
		//update item
		$this->db->setQuery( "UPDATE #__content SET sectionid='$section_id', catid='$new_cat_id', ordering='$new_order' WHERE id='$item_id'"	);
		if (!$this->db->query()) {
			echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
			exit();
		}	
		
		//reorder old category so as to leave things nicely
		$this->reorderItemsCategory($old_cat_id);
		
		$url = 'index2.php?option=com_pi_pages_and_items&task=page&sub_task=edit&type=content_blog_category&pageId='.$new_parent_id;	
		$this->redirect_to_url( $url, _pi_lang_item_moved);	
		
	}	
	
	function truncate_string($string, $length){
		$dots='...';
		$string = trim($string);		
		if(strlen($string)<=$length){
			return $string;	
		}
		if(!strstr($string," ")){
			return substr($string,0,$length).$dots;
		}	
		$lengthf = create_function('$string','return substr($string,0,strrpos($string," "));');	
		$string = substr($string,0,$length);	
		$string = $lengthf($string);
		while(strlen($string)>$length){
			$string=$lengthf($string);
		}	
		return $string.$dots;
	}
	
	function delete_plugin_items($item_id, $item_type){
	
	
		if(file_exists(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/itemtypes/'.$item_type.'/'.$item_type.'.php')){
		
			//if the class for specific itemtype is not there yet, go get it
			$class_name = 'class_itemtype_'.$item_type;
			if (!class_exists($class_name)){    
				require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/itemtypes/'.$item_type.'/'.$item_type.'.php');						
			}
			$class_itemtype = new $class_name();			
			//check if function 'item_delete' is there, if so, do it
			if(method_exists($class_itemtype,'item_delete')){
				//$class_itemtype->item_delete();
				$class_itemtype->item_delete($item_id);
			}
		}				
	}
	
	function send_notification($subject, $message){
		//get mailadress(es)
		$usergroup = $this->usergroup;
		$this->db->setQuery("SELECT email FROM #__pi_aua_usergroups WHERE id='$usergroup' LIMIT 1");
		$rows = $this->db->loadObjectList();
		$row = $rows[0];
		$email = $row->email;	
		
		$email_array = explode(',', $email);
		
		//get from-adress and name from pi_admin_user_access				
		$from_mail = $this->user_access_config['notify_from_address'];
		if($this->user_access_config['notify_from_name']){
			//aua version 1.2.8
			$from_name = $this->user_access_config['notify_from_name'];
		}else{
			$from_name = '';
		}
		
		//if($email){
		foreach($email_array as $mailadress){
			if(defined('_JEXEC')){
				//joomla 1.5
				//JUtility::sendMail($from_mail, $from_name, $email, $subject, $message);
				JUtility::sendMail($from_mail, $from_name, $mailadress, $subject, $message);				
			}else{
				//joomla 1.0.x
				//mosMail($from_mail, $from_name, $email, $subject, $message);
				mosMail($from_mail, $from_name, $mailadress, $subject, $message);
			}
		}
	}	
	
	function image_file_delete(){
		//get fileToDelete
		$fileToDelete = $this->get_var('fileToDelete');
		
		//delete the file
		unlink("../images/stories/$fileToDelete");
		
		$this->redirect_to_url("index2.php?option=com_pi_pages_and_items&task=image_select", _pi_lang_image_deleted);
	}
	
	function image_upload_process(){
		
		$new_name = "";
		$error = 0;
		
		if ($_FILES['image']['name']!=''){
	
			$userfile_name = strtolower($_FILES['image']['name']);			
			$userfile_tmp = $_FILES['image']['tmp_name'];
			$userfile_size = $_FILES['image']['size'];
			
			if($userfile_size>=$this->pi_config['image_maxsize']){
				$message = _pi_lang_filetoobig;	
				$error = 1;		
			}
				
			// get extension
			$extension = explode(".", $userfile_name);
			$last = count($extension) - 1;
			$extension = strtolower("$extension[$last]");
			
			//check extension				
			$allowed_extensions = explode(",", $this->pi_config['image_filetypes']);			
			if (!in_array($extension, $allowed_extensions)){
				$message = _pi_lang_wrong_filetype.$this->pi_config['image_filetypes'];	
				$error = 1;	
			}
			
			//rewrite jpeg to jpg
			if($extension=='jpeg'){
				$extension = 'jpg';
			}	
			
			// get the old name of the file	
			$old_name = str_replace('.'.$extension,'',$userfile_name);				
			
			//rename file if already exist
			if(file_exists($this->pi_config['image_dir'].$old_name.'.'.$extension)){			
				$j = 2;
				while (file_exists($this->pi_config['image_dir'].$old_name.'-'.$j.".".$extension)){
					$j = $j + 1;
				}
				$new_name = $old_name . "-" . $j;	
			}else{
				$new_name = $old_name;
			}
			
			//replace spaces by underscores
			$new_name = str_replace(' ', '_', $new_name);	
			
			//upload file
			$file_destination = $this->pi_config['image_dir'].$new_name.'.'.$extension;
			if($error==0){	
				if(move_uploaded_file($userfile_tmp, $file_destination)){
					$new_name = $new_name.".".$extension; 
					$message = $new_name.' '._pi_lang_succes_upload; 
					
					//get sizes and ratio
					$sizes = getimagesize($file_destination);	
					$aspect_ratio = $sizes[1]/$sizes[0]; 
					
					//resize uploaded image  
					if ($sizes[0] > $this->pi_config['image_max_width'] || $sizes[1] > $this->pi_config['image_max_height']){
						
						$widthratio = $sizes[0]/$this->pi_config['image_max_width']; 			
						$heightratio = $sizes[1]/$this->pi_config['image_max_height']; 			
			
						$imgnewwidth = $this->pi_config['image_max_width']; 
						$imgnewheight = $this->pi_config['image_max_height']; 
			
						if($widthratio <= $heightratio){ 
							$imgnewwidth = $sizes[0]/$heightratio; 					
							$newwidth = round($imgnewwidth); 
							$newheight = round($imgnewheight); 					
							 
						}else{ 
							$imgnewheight = $sizes[1]/$widthratio;						
							$newwidth = round($imgnewwidth); 
							$newheight = round($imgnewheight); 					
						}
						
						$imgnew = imagecreatetruecolor($newwidth,$newheight);				
						if($extension=='jpg'){
							$srcimg=imagecreatefromjpeg($file_destination)or die(_pi_lang_problemopeningimage);
						}elseif($extension=='gif'){
							$srcimg=imagecreatefromgif($file_destination)or die(_pi_lang_problemopeningimage);
						}elseif($extension=='png'){
							$srcimg=imagecreatefrompng($file_destination)or die(_pi_lang_problemopeningimage);
						}
						if(function_exists('imagecopyresampled')){
							imagecopyresampled($imgnew,$srcimg,0,0,0,0,$newwidth,$newheight,ImageSX($srcimg),ImageSY($srcimg))or die(_pi_lang_problemresizing);
						}else{
							imagecopyresized($imgnew,$srcimg,0,0,0,0,$newwidth,$newheight,ImageSX($srcimg),ImageSY($srcimg))or die(_pi_lang_problemresizing);
						}				
						if($extension=='jpg'){
							imagejpeg($imgnew,$file_destination,90)or die(_pi_lang_problemsaving);
						}elseif($extension=='gif'){
							imagegif($imgnew,$file_destination)or die(_pi_lang_problemsaving);
						}elseif($extension=='png'){
							imagepng($imgnew,$file_destination)or die(_pi_lang_problemsaving);
						}								
					} 					           
				}else{		
					$message = _pi_lang_not_upload;	
					$error = 1;		
				}	
			}	
		}else{
			$message = _pi_lang_no_file;
			$error = 1;		
		}
		if($message){
			$message = "&message=$message";
		}	
		if($error == 1){
			$new_name = '';
		}
		
		$this->redirect_to_url("index2.php?option=com_pi_pages_and_items&task=image_upload&image_uploaded=$new_name$message");
	}
	
	function page_save(){
		
		//get vars
		$pageId = $this->get_var('pageId', '', 'post');
		$menutype = $this->get_var('menutype', '', 'post');
		$pageComponentId = $this->get_var('pageComponentId');
		$titleShort = $this->get_var('titleShort');		
				
		$link = $this->get_var('link');
		$content_page = $this->get_var('content_page');	
		$show_in_menu = $this->get_var('show_in_menu');
		$categoryPublished = $this->get_var('categoryPublished');
		$subsub_task = $this->get_var('subsub_task', '', 'post');
		$page_parent = $this->get_var('pageParent');
		$cat_id = intval($this->get_var('cat_id'));
		if(defined('_JEXEC')){
			//joomla 1.5
			$titleShort = addslashes($titleShort);
		}
		$alias = $this->get_var('alias', '');
		if($alias==''){
			$alias = $this->make_alias($titleShort);
		}		
		
		//make alias unique
		if($this->pi_config['make_page_alias_unique']){
			$alias = $this->make_alias_unique($alias, 'categories', $cat_id);
		}	
		
		//if user has no rights to publish set to not published
		if($this->checkUserActionRight(5)!=true){
			$categoryPublished = 0;
		}
		//if category gets unpublished, menuitem should also unpublish
		if($categoryPublished==0){
			$show_in_menu=0;
		}
		
		//if not content category blog type	
		if(!$content_page){
			$show_in_menu = $this->get_var('show_in_menu');				
		}
		
		$browserNav = $this->get_var('browserNav');
		$access = $this->get_var('access');
		$access_category = $this->get_var('access_category');
		$params = $this->get_var('params');
		
		$pages_are_reordered = $this->get_var('pages_are_reordered','');		
		$pages_total = $this->get_var('pages_total');
		$items_are_reordered = $this->get_var('items_are_reordered','');
		$items_total = $this->get_var('items_total', '');
		
		$sub_task = $this->get_var('sub_task');
		$pageType = $this->get_var('pageType');
		$section_id = $this->get_var('section');
		$section_id_old = $this->get_var('section_id_current');
		if( defined('_JEXEC') ){
			//joomla 1.5
			$default_home = intval($this->get_var('default_home'));
			$default_home_current = intval($this->get_var('default_home_current'));
			if($default_home==1 && $default_home_current==0){
				//this page becomes new homepage so un-homepage the current homepage
				foreach($this->menuitems as $row){
					if($row->home==1){
						$current_home = $row->id;
						break;
					}
				}			
				$this->db->setQuery( "UPDATE #__menu SET home='0' WHERE id='$current_home'"	);
				$this->db->query();
			}		
		}	
		
		//make a nice string from parameters
		$paramsString = '';
		for($n = 0; $n < count($params); $n++){
			$row = each($params);			
			$value = $row['value'];	
			if(defined('_JEXEC')){
				//joomla 1.5
				$value = addslashes($value);
			}									
			$paramsString .="\n$row[key]=$value";	
		}		
		
		if($sub_task=='new'){			
			if($content_page){
				//is content category blog page	
					
				$this->db->setQuery("SELECT count FROM #__sections WHERE id='$section_id' LIMIT 1"  );
				$rows = $this->db->loadObjectList();
				$row = $rows[0];							
				$numberOfCategories = $row->count;				
		
				//new number of categories
				$numberOfCategories = $numberOfCategories+1;
			
				//insert new category				
				if( defined('_JEXEC') ){
					//if joomla version 1.5 write page_title to 'alias' column instead of 'name' column in joomla 1.0.x (why?!)
					$this->db->setQuery( "INSERT INTO #__categories SET alias='$alias', title='$titleShort', section='$section_id', image_position='left', published='$categoryPublished', access='$access'");
				}else{
					//category name and title have addslashes in Joomla 1.0.x for some wierd reason. probably double escaped somewhere
					$cat_name = addslashes($titleShort);
					$this->db->setQuery( "INSERT INTO #__categories SET name='$cat_name', title='$cat_name', section='$section_id', image_position='left', published='$categoryPublished', access='$access'");
				}			
				if (!$this->db->query()) {
					echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
					exit();
				}			
				$categoryId = $this->db->insertid();
			
				//update section			
				/*
				$this->db->setQuery( "UPDATE #__sections SET count='$numberOfCategories' WHERE id='$section_id'"	);
				if (!$this->db->query()) {
					echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
					exit();
				}
				*/
				
				//compose menu-link
				//for joomla 1.5 a new link is used
				if( defined('_JEXEC') ){
					$catbloglink = 'index.php?option=com_content&view=category&layout=blog&id=';
				}else{
					$catbloglink = 'index.php?option=com_content&task=blogcategory&id=';
				}
				$pageLink = $catbloglink.$categoryId;
				
				//add categoryId to params-string
				$paramsString = $paramsString."\ncategoryid=".$categoryId;
			
			}else{//end if content_page
			
				//compose menu-link
				$pageLink = $link;	
				$paramsString = $this->get_var('parameters');
			}
		
			//reorder mainmenu to make sure new menu-item is last		
			//$this->db->setQuery("SELECT id, ordering FROM #__menu WHERE menutype='mainmenu' AND parent='$pageId' ORDER BY ordering ASC");
			$this->db->setQuery("SELECT id, ordering FROM #__menu WHERE parent='$pageId' ORDER BY ordering ASC");
			$rows = $this->db->loadObjectList();		
			$counter = 1;
			foreach($rows as $row){
				$rowId = $row->id;
				$order = $row->ordering;
				
				$this->db->setQuery( "UPDATE #__menu SET ordering='$counter' WHERE id='$rowId'"	);
				if (!$this->db->query()) {
					echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
					exit();
				}			
				
				$counter = $counter+1;
			}
			
			//get the parent-menuitem's sublevel. Only for 1.5.x, in 1.0.x this never seemed to have worked at all.			
			$sublevel = $this->get_sublevel_add_one($pageId);
			
			//insert new menuitem in mainmenu	
			//for joomla 1.5 component_id for category blog content is 20 and name goes into alias and access goes into 'access', default_home to home.
			if( defined('_JEXEC') ){						
				$this->db->setQuery( "INSERT INTO #__menu SET menutype='$menutype', name='$titleShort', alias='$alias', link='$pageLink', browserNav='$browserNav', access='$access_category', type='$pageType', published='$show_in_menu', parent='$pageId', sublevel='$sublevel', componentid='20', ordering='$counter', params='$paramsString', home='$default_home'");
			}else{
				//joomla 1.0.x
				$this->db->setQuery( "INSERT INTO #__menu SET menutype='$menutype', name='$titleShort', link='$pageLink', browserNav='$browserNav', utaccess='$access_category', type='$pageType', published='$show_in_menu', parent='$pageId', componentid='$categoryId', ordering='$counter', params='$paramsString'");			
			}		
			if (!$this->db->query()) {
				echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
				exit();
			}
			$menuId = $this->db->insertid();
			
			//if using the user-access component for Pi give this author's usergroup rights for this page
			if($this->pi_config['use_user_access_component']){	
				if($this->user_access_config['active_pagesaccess'] && $this->user_type!="Super Administrator"){				
					$this->class_ua->set_page_access_group($menuId, $this->usergroup);									
				}	
				//if using the inherit rights option, let all usergroups inherit rights				
				if($this->user_access_config['inherit_rights_parent_page']){					
					$this->class_ua->set_page_access_all_groups($menuId, $page_parent);					
				}				
			}		
			
			//send new-page-notification if configed to do so
			if(!$this->checkUserActionRight(8)  && $this->user_type!='Super Administrator'){
				$subject = _pi_lang_notify_new_page_1;
				$message = _pi_lang_notify_hello.",\n\n";
				$message .= _pi_lang_notify_new_page_2.":\n";
				$message .= $this->live_site."\n\n";
				$message .= _pi_lang_notify_new_item_by.":\n";				
				$message .= $this->get_username()."\n\n";				
				$message .= _pi_lang_notify_page_1."\n";				
				if(defined('_JEXEC')){
					//joomla 1.5
					$url = 'index.php?option=com_content&view=category&layout=blog&id='.$categoryId.'&Itemid='.$pageId;					
				}else{
					//joomla 1.0.x
					$url = 'index.php?option=com_content&task=blogcategory&id='.$categoryId.'&Itemid='.$pageId;
				}				
				$message .= $this->live_site.$url."\n\n";				
				$message .= _pi_lang_notify_page_3.":\n";
				$message .= $this->live_site.'index2.php?option=com_pi_pages_and_items&task=page&sub_task=edit&pageId='.$pageId."\n\n";				
				$message .= _pi_lang_notify_title_page."\n";
				$message .= $titleShort."\n\n";		
				$this->send_notification($subject, $message);
			}		
		
		// end if new page
		}else{
		//if page update
			
			//for all menulink types other then category blog
			if(!$content_page){		
				$paramsString = $this->get_var('parameters');
			}
						
			//update menuitem
			//joomla 1.5 also writes name to alias column, acces to 'access', default_home to home
			if( defined('_JEXEC') ){				
				$this->db->setQuery( "UPDATE #__menu SET name='$titleShort', alias='$alias', link='$link', browserNav='$browserNav', access='$access', published='$show_in_menu', params='$paramsString', home='$default_home' WHERE id='$pageId'"	);
			}else{
				$this->db->setQuery( "UPDATE #__menu SET name='$titleShort', link='$link', browserNav='$browserNav', utaccess='$access', published='$show_in_menu', params='$paramsString' WHERE id='$pageId'"	);		
			}			
			if (!$this->db->query()) {
				echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
				exit();
			}
			
			//update category
			//joomla 1.5 write to alias column and not to name, access to 'access'
			if( defined('_JEXEC') ){
				//joomla 1.5	
				$this->db->setQuery( "UPDATE #__categories SET title='$titleShort', alias='$alias', published='$categoryPublished', access='$access_category', section='$section_id' WHERE id='$cat_id'");
			}else{
				//joomla 1.0.x
				$this->db->setQuery( "UPDATE #__categories SET name='$titleShort', title='$titleShort', published='$categoryPublished', access='$access_category', section='$section_id' WHERE id='$cat_id'");
			}
			if (!$this->db->query()) {
				echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
				exit();
			} 
				
			//if pages where reordered update the ordering of these pages
			if($pages_are_reordered==1){						
				for ($n = 1; $n <= $pages_total; $n++){
					$temp_id = intval($this->get_var('reorder_page_id_'.$n, '', 'post'));			
					$this->db->setQuery( "UPDATE #__menu SET ordering='$n' WHERE id='$temp_id'"	);
					if (!$this->db->query()) {
						echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
						exit();
					}								
				}
			}
							
			//if items where reordered update the ordering of these items	
			if($items_are_reordered==1){									
				for ($n = 1; $n <= $items_total; $n++){		
					$temp_id = intval($this->get_var('reorder_item_id_'.$n, '', 'post'));
						//exit('temp='.$temp_id.'n='.$n);					
					$this->db->setQuery( "UPDATE #__content SET ordering='$n' WHERE id='$temp_id'"	);
					if (!$this->db->query()) {
						echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
						exit();
					}					 								
				}
			}
		
			//send edit-page-notification if configed to do so
			if(!$this->checkUserActionRight(9)  && $this->user_type!='Super Administrator'){
				$subject = _pi_lang_notify_page_edit_1;	
				$message = _pi_lang_notify_hello.",\n\n";
				$message .= _pi_lang_notify_page_edit_2."\n";
				$message .= $this->live_site."\n\n";
				$message .= _pi_lang_notify_new_item_by.":\n";				
				$message .= $this->get_username()."\n\n";
				$message .= _pi_lang_notify_page_1."\n";
				if(defined('_JEXEC')){
					//joomla 1.5
					$url = 'index.php?option=com_content&view=category&layout=blog&id='.$cat_id.'&Itemid='.$pageId;					
				}else{
					//joomla 1.0.x
					$url = 'index.php?option=com_content&task=blogcategory&id='.$cat_id.'&Itemid='.$pageId;
				}				
				//$message .= "$this->live_site/index.php?option=com_content&task=blogcategory&id=$pageComponentId&Itemid=$pageId\n\n";
				$message .= $this->live_site.$url."\n\n";
				$message .= _pi_lang_notify_page_3.":\n";
				$message .= $this->live_site.'index2.php?option=com_pi_pages_and_items&task=page&sub_task=edit&pageId='.$pageId."\n\n";				
				$message .= _pi_lang_notify_title_page."\n";
				$message .= $titleShort."\n\n";	
				$this->send_notification($subject, $message);
			}
			
			//update sectionid content and underlying pages only if section_id changed
			if($section_id_old!=$section_id){
				//update sectionid underlying pages
				if($this->pi_config['child_inherit_from_parent_change']){
					$this->section_update_children($pageId, $section_id);
				}
				//update sectionid of content-items in category		
				$this->update_items_category($cat_id, $section_id);
			}	
			
		}//end if page update
		
		//clean cache
		$this->clean_cache_menu();
		
		//clean item-index
		$this->keep_item_index_clean();
		
		if($sub_task=='edit'){
			if($subsub_task=='apply'){
				$url = "index2.php?option=com_pi_pages_and_items&task=page&sub_task=edit&pageId=$pageId";
			}else{
				//normal save so go to parent page
				if($page_parent==0){
					$url = "index2.php?option=com_pi_pages_and_items&task=root&menutype=".$menutype;
				}else{
					$url = "index2.php?option=com_pi_pages_and_items&task=page&sub_task=edit&pageId=$page_parent";
				}
			}
		}else{
			//new page
			if($subsub_task=='apply'){
				$url = "index2.php?option=com_pi_pages_and_items&task=page&sub_task=edit&pageId=$menuId";
			}else{
				//normal save so go to parent page
				if($page_parent==0){
					$url = "index2.php?option=com_pi_pages_and_items&task=root&menutype=".$menutype;
				}else{
					$url = "index2.php?option=com_pi_pages_and_items&task=page&sub_task=edit&pageId=$page_parent";
				}
			}
		}
		$this->redirect_to_url($url, _pi_lang_page_saved);
	}
	
	function page_trash(){
		global $pageId, $pageId, $pageType;
	
		//only if user has rights
		if($this->checkUserActionRight(6)!=true){
			echo '<script> alert(\''._pi_lang_no_trash_page.'\'); window.history.go(-1); </script>';
			exit();	
		}
			
		foreach($this->menuitems as $row){				
			if($row->id==$pageId){
				$parentPageId = $row->parent;
				$menutype = $row->menutype;							
			}
		}	
		
		//trash this page and all underlying pages and all items on these pages
		$this->trashPage($pageId);
		
		if($parentPageId=='0'){
			//go to root
			$this->redirect_to_url("index2.php?option=com_pi_pages_and_items&task=root&menutype=$menutype", _pi_lang_page_trashed);
		}
		
		$this->redirect_to_url("index2.php?option=com_pi_pages_and_items&task=page&sub_task=edit&pageId=$parentPageId", _pi_lang_page_trashed);		
	}
	
	function root_save(){
		$pages_total = $this->get_var('pages_total');
		$pages_are_reordered = $this->get_var('pages_are_reordered');	
		
		//if pages where reordered update the ordering of these pages
		if($pages_are_reordered==1){						
			for ($n = 1; $n <= $pages_total; $n++){
				$temp_id = intval($this->get_var('reorder_page_id_'.$n, '', 'post'));			
				$this->db->setQuery( "UPDATE #__menu SET ordering='$n' WHERE id='$temp_id'"	);
				if (!$this->db->query()) {
					echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
					exit();
				}								
			}
		}
		
		$this->redirect_to_url("index2.php?option=com_pi_pages_and_items", _pi_lang_pageorder_saved);
	}
	
	/*
	function check_for_updates($from){			
		echo '<div id="update_checker"><iframe src="http://www.pages-and-items.com/index2.php?option=com_update_checker&amp;extension=pi&amp;version='.$this->pi_config['version'].'&amp;from='.$from.'&amp;language='.$this->pi_config['language'].'" width="500" height="50" frameborder="0" marginwidth="0" marginheight="0" name="iframe_update_checker" style="overflow: hidden;"></iframe></div>';		
	}
	*/
	
	function cancel(){
		global $pageId;
		
		if($pageId=='0'){
			$this->redirect_to_url("index2.php?option=com_pi_pages_and_items&task=root", _pi_lang_action_canceled);
		}else{
			$this->redirect_to_url("index2.php?option=com_pi_pages_and_items&task=page&sub_task=edit&pageId=$pageId", _pi_lang_action_canceled);
		}	
	}
	
	function translate_item_type($item_type){			
		if($item_type=='text'){
			$plugin_name = _pi_lang_itemtypetext;
		}elseif($item_type=='html'){
			$plugin_name = 'HTML';
		}elseif($item_type=='other_item'){
			$plugin_name = _pi_lang_itemtype_other_item;
		}else{
			if (file_exists(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/itemtypes/'.$item_type.'/language/'.$this->pi_config['language'].'.php')){
				include(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/itemtypes/'.$item_type.'/language/'.$this->pi_config['language'].'.php');					
				$plugin_name = $pi_lang_plugin['name'];						
			}else{			
				if(file_exists(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/itemtypes/'.$item_type.'/language/english.php')){
					include(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/itemtypes/'.$item_type.'/language/english.php'); 									
					$plugin_name = $pi_lang_plugin['name'];				
				}else{
					if(strpos($item_type, 'ustom_')){
						//custom itemtype						
						$pos = strpos($item_type, 'ustom_');
						$type_id = substr($item_type, $pos+6, strlen($item_type));	
						$this->db->setQuery("SELECT name FROM #__pi_customitemtypes WHERE id='$type_id' LIMIT 1");
						$rows = $this->db->loadObjectList();
						$row = $rows[0];								
						$plugin_name = $row->name;						
						
					}else{
						//itemtype not installed
						$plugin_name = false;
					}	
				}

			}		
		}
		return $plugin_name;
	}
	
	function make_alias($alias){	
		if(defined('_JEXEC')){
			//joomla 1.5
			$alias = str_replace("'",'',$alias);
			$alias = str_replace('"','',$alias);
			$alias = JFilterOutput::stringURLSafe($alias);
		}else{
			//joomla 1.0.x
			$alias = str_replace(' ','-',$alias);
			$alias = str_replace('_','',$alias);		
			$alias = str_replace("'",'',$alias);
			$alias = str_replace('"','',$alias);
			$alias = str_replace('/','',$alias);
			$alias = str_replace('\\','',$alias);
		}		
		return $alias;
	}
	
	function display_footer(){		
		echo '<div class="smallgrey" id="pi_footer"><a href="http://www.pages-and-items.com" target="_blank">Pages-and-Items</a> &copy; '._pi_lang_version.' '.$this->version.'  <a href="http://www.gnu.org/licenses/gpl-2.0.html" target="_blank">GNU/GPL License</a></div>';
	}
	
	function config_save(){			
		
		if( defined('_JEXEC') ){
			//joomla 1.5	
			$version = '1_5';
		}else{
			//joomla 1.0.x	
			$version = '1_0';
		}

		//hack or unhack TinyMCE's image popup file
		$action = $this->get_var('image_popup_action', 'do_nothing');
		if($action=='do_hack'){
			//read hacked version
			//check if readable, open, read and close	
			if (!$fp = @fopen(dirname(__FILE__).'/../com_pi_pages_and_items/tinymce_popup/image_modified.htm', "rb")) {			
				die('problem reading the image-popup file: /administrator/components/com_pi_pages_and_items/tinymce_popup/image_modified.htm');
				return false;
			}	
			$hacked_image_file = fread($fp, 16000);
			fclose ($fp);
			
			//write to image.htm
			//check if writeable, open, write and close	
			if (!$fp = @fopen(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/editors/tinymce/jscripts/tiny_mce/plugins/advimage/image.htm', "wb")) {	
				die('file: /'.$this->plugin_dir.'/editors/tinymce/jscripts/tiny_mce/plugins/advimage/image.htm is not writable');
				return false;
			}		
			fputs($fp, $hacked_image_file, strlen($hacked_image_file));
			fclose ($fp);
			
			//read hacked version
			//check if readable, open, read and close	
			if (!$fp = @fopen(dirname(__FILE__).'/tinymce_popup/popsize_image_'.$version.'.js', "rb")) {			
				die('problem reading the image-popup file: /administrator/components/com_pi_pages_and_items/tinymce_popup/popsize_image_'.$version.'.js');
				return false;
			}	
			$hacked_image_popsize_file = fread($fp, 5000);
			fclose ($fp);
			
			//write to editor_plugin.js
			//check if writeable, open, write and close	
			if (!$fp = @fopen(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/editors/tinymce/jscripts/tiny_mce/plugins/advimage/editor_plugin.js', "wb")) {	
				die('file: /'.$this->plugin_dir.'/editors/tinymce/jscripts/tiny_mce/plugins/advimage/editor_plugin.js is not writable');
				return false;
			}		
			fputs($fp, $hacked_image_popsize_file, strlen($hacked_image_popsize_file));
			fclose ($fp);
			
		}else if($action=='do_unhack'){
			//read original version
			//check if readable, open, read and close	
			if (!$fp = @fopen(dirname(__FILE__).'/tinymce_popup/image_backup.htm', "rb")) {				
				die('problem reading the image-popup file: /administrator/components/com_pi_pages_and_items/tinymce_popup/image_backup.htm');
				return false;
			}	
			$original_image_file = fread($fp, 13000);
			fclose ($fp);	
			
			//write to image.htm
			//check if writeable, open, write and close	
			if (!$fp = @fopen(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/editors/tinymce/jscripts/tiny_mce/plugins/advimage/image.htm', "wb")) {	
				die('file: /'.$this->plugin_dir.'/editors/tinymce/jscripts/tiny_mce/plugins/advimage/image.htm is not writable');
				return false;
			}		
			fputs($fp, $original_image_file, strlen($original_image_file));
			fclose ($fp);	
			
			//read original version
			//check if readable, open, read and close	
			if (!$fp = @fopen(dirname(__FILE__).'/tinymce_popup/popsize_image_'.$version.'_backup.js', "rb")) {			
				die('problem reading the image-popup file: /administrator/components/com_pi_pages_and_items/tinymce_popup/popsize_image_'.$version.'_backup.js');
				return false;
			}	
			$hacked_image_popsize_file = fread($fp, 5000);
			fclose ($fp);
			
			//write to editor_plugin.js
			//check if writeable, open, write and close	
			if (!$fp = @fopen(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/editors/tinymce/jscripts/tiny_mce/plugins/advimage/editor_plugin.js', "wb")) {	
				die('file: /'.$this->plugin_dir.'/editors/tinymce/jscripts/tiny_mce/plugins/advimage/editor_plugin.js is not writable');
				return false;
			}		
			fputs($fp, $hacked_image_popsize_file, strlen($hacked_image_popsize_file));
			fclose ($fp);
			
		}//end if undo hack
		
		//links and downloads
		//hack or unhack TinyMCE's link popup file
		$action_link = $this->get_var('link_popup_action', 'do_nothing');
		if($action_link=='do_hack'){
			//read hacked version
			//check if readable, open, read and close	
			if (!$fp = @fopen(dirname(__FILE__).'/tinymce_popup/link_modified.htm', "rb")) {			
				die('problem reading the link-popup file: /administrator/components/com_pi_pages_and_items/tinymce_popup/link_modified.htm');
				return false;
			}	
			$hacked_link_file = fread($fp, 25000);
			fclose ($fp);
			
			//write to link.htm
			//check if writeable, open, write and close	
			if (!$fp = @fopen(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/editors/tinymce/jscripts/tiny_mce/plugins/advlink/link.htm', "wb")) {				
				die('file: /'.$this->plugin_dir.'/editors/tinymce/jscripts/tiny_mce/plugins/advlink/link.htm is not writable');
				return false;
			}		
			fputs($fp, $hacked_link_file, strlen($hacked_link_file));
			fclose ($fp);
			
			//read hacked version
			//check if readable, open, read and close	
			if (!$fp = @fopen(dirname(__FILE__).'/../com_pi_pages_and_items/tinymce_popup/popsize_link_'.$version.'.js', "rb")) {			
				die('problem reading the image-popup file: /administrator/components/com_pi_pages_and_items/tinymce_popup/popsize_link_'.$version.'.js');
				return false;
			}	
			$hacked_link_popsize_file = fread($fp, 5000);
			fclose ($fp);
			
			//write to editor_plugin.js
			//check if writeable, open, write and close	
			if (!$fp = @fopen(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/editors/tinymce/jscripts/tiny_mce/plugins/advlink/editor_plugin.js', "wb")) {	
				die('file: /'.$this->plugin_dir.'/editors/tinymce/jscripts/tiny_mce/plugins/advlink/editor_plugin.js is not writable');
				return false;
			}		
			fputs($fp, $hacked_link_popsize_file, strlen($hacked_link_popsize_file));
			fclose ($fp);			
			
		}else if($action_link=='do_unhack'){
			//read original version
			//check if readable, open, read and close	
			if (!$fp = @fopen(dirname(__FILE__).'/../com_pi_pages_and_items/tinymce_popup/link_backup.htm', "rb")) {			
				die('problem reading the link-popup file: /administrator/components/com_pi_pages_and_items/tinymce_popup/link_backup.htm');
				return false;
			}	
			$original_link_file = fread($fp, 17000);
			fclose ($fp);	
			
			//write to link.htm
			//check if writeable, open, write and close	
			if (!$fp = @fopen(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/editors/tinymce/jscripts/tiny_mce/plugins/advlink/link.htm', "wb")) {	
				die('file: /'.$this->plugin_dir.'/editors/tinymce/jscripts/tiny_mce/plugins/advlink/link.htm is not writable');
				return false;
			}		
			fputs($fp, $original_link_file, strlen($original_link_file));
			fclose ($fp);	
			
			//read original version
			//check if readable, open, read and close	
			if (!$fp = @fopen(dirname(__FILE__).'/../com_pi_pages_and_items/tinymce_popup/popsize_link_'.$version.'_backup.js', "rb")) {			
				die('problem reading the image-popup file: /administrator/components/com_pi_pages_and_items/tinymce_popup/popsize_link_'.$version.'_backup.js');
				return false;
			}	
			$original_link_popsize_file = fread($fp, 3000);
			fclose ($fp);
			
			//write to editor_plugin.js
			//check if writeable, open, write and close	
			if (!$fp = @fopen(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/editors/tinymce/jscripts/tiny_mce/plugins/advlink/editor_plugin.js', "wb")) {	
				die('file: /'.$this->plugin_dir.'/editors/tinymce/jscripts/tiny_mce/plugins/advlink/editor_plugin.js is not writable');
				return false;
			}		
			fputs($fp, $original_link_popsize_file, strlen($original_link_popsize_file));
			fclose ($fp);			
			
		}

		
		
		//get plugin_syntax_cheatcheat
		if( defined('_JEXEC') ){
			//joomla 1.5
			$plugin_syntax_cheatcheat = JRequest::getVar('plugin_syntax_cheatcheat','','post','string', JREQUEST_ALLOWRAW);	
		}else{
			//joomla 1.0.x
			$plugin_syntax_cheatcheat = mosGetParam( $_POST, 'plugin_syntax_cheatcheat','', _MOS_ALLOWRAW);
		}		
		//clean lines
		$plugin_syntax_cheatcheat = str_replace('
','[newline]',$plugin_syntax_cheatcheat);
		$plugin_syntax_cheatcheat = str_replace('=','[equal]',$plugin_syntax_cheatcheat);
		$plugin_syntax_cheatcheat = addslashes($plugin_syntax_cheatcheat);			
		
		
		//get custom redirect url
		if( defined('_JEXEC') ){
			//joomla 1.5
			$item_save_redirect_url = JRequest::getVar('item_save_redirect_url','','post','string', JREQUEST_ALLOWRAW);	
		}else{
			//joomla 1.0.x
			$item_save_redirect_url = mosGetParam( $_POST, 'item_save_redirect_url','', _MOS_ALLOWRAW);
		}		
		//clean lines		
		$item_save_redirect_url = str_replace('=','[equal]',$item_save_redirect_url);				
		
		//menus
		$menus = $this->get_var('menus',array(0));
		//if menutype is not selected, take it out of array
		//added the 'm' because of the problem with numerical indexes when unsetting in loop
		$loops = count($menus);
		for($n = 0; $n <= $loops; $n++){
			if(!isset($menus['m'.$n]['menutype'])){		
				unset ($menus['m'.$n]);					
			} 	
		}
		
		//sort array by order
		foreach ($menus as $key => $row) {
			$order[$key] = $row['order'];    
		}
		
		if(count($menus)!=0){
			array_multisort($order, SORT_ASC, $menus);
		}
		
		//write menus array to config string
		$menu_string = '';		
		if (is_array($menus)){
			$counter = 0;	
			foreach($menus as $menu){
				//$config .= '\''.$menu[menutype].'\' => \''.$menu[title].'\',';
				if($counter!=0){
					$menu_string .= ',';
				}
				$menu_string .= $menu['menutype'].';'.$menu['title'];				
				$counter = $counter+1;
			}				
		}		
				
		$config = 'language='.$this->get_var('language', 'english').'
use_pi_frontend_editting='.$this->get_var('use_pi_frontend_editting', 'false').'
menus='.$menu_string.'
cit=1
use_user_access_component='.$this->get_var('use_user_access_component', 'false').'
item_props_publish='.$this->get_var('item_props_publish', 'false').'
item_show_frontpage_option='.$this->get_var('item_show_frontpage_option', 'false').'
item_menu='.$this->get_var('item_menu', 'tabs').'
item_props_alias='.$this->get_var('item_props_alias', 'false').'
plugin_syntax_cheatcheat='.$plugin_syntax_cheatcheat.'
allow_authors_to_publish='.$this->get_var('allow_authors_to_publish', 'false').'
allow_editors_to_publish='.$this->get_var('allow_editors_to_publish', 'false').'
make_article_alias_unique='.$this->get_var('make_article_alias_unique', 'false').'
date_format='.$this->get_var('date_format', '%Y-%m-%d').'
create_sef_urls='.$this->get_var('create_sef_urls', '0').'
sef_url_cat='.$this->get_var('sef_url_cat', '0').'
sef_url_id='.$this->get_var('sef_url_id', '0').'
sef_url_ext='.$this->get_var('sef_url_ext', '').'
item_save_redirect='.$this->get_var('item_save_redirect', 'category_blog').'
item_save_redirect_url='.$item_save_redirect_url.'
item_props_title='.$this->get_var('item_props_title', 'false').'
item_props_access='.$this->get_var('item_props_access', 'false').'
item_props_author_alias='.$this->get_var('item_props_author_alias', 'false').'
item_props_author='.$this->get_var('item_props_author', 'false').'
item_props_created_date='.$this->get_var('item_props_created_date', 'false').'
item_props_publish_up='.$this->get_var('item_props_publish_up', 'false').'
item_props_publish_down='.$this->get_var('item_props_publish_down', 'false').'
item_props_hits='.$this->get_var('item_props_hits', 'false').'
item_props_version='.$this->get_var('item_props_version', 'false').'
item_props_created='.$this->get_var('item_props_created', 'false').'
item_props_modified='.$this->get_var('item_props_modified', 'false').'
item_props_item_id='.$this->get_var('item_props_item_id', 'false').'
item_props_category_id='.$this->get_var('item_props_category_id', 'false').'
item_props_section_id='.$this->get_var('item_props_section_id', 'false').'
item_props_other_items='.$this->get_var('item_props_other_items', 'false').'
item_props_show_title='.$this->get_var('item_props_show_title', 'false').'
item_props_linked_titles='.$this->get_var('item_props_linked_titles', 'false').'
item_props_intro='.$this->get_var('item_props_intro', 'false').'
item_props_section='.$this->get_var('item_props_section', 'false').'
item_props_section_link='.$this->get_var('item_props_section_link', 'false').'
item_props_category='.$this->get_var('item_props_category', 'false').'
item_props_category_link='.$this->get_var('item_props_category_link', 'false').'
item_props_rating='.$this->get_var('item_props_rating', 'false').'
item_props_author_names='.$this->get_var('item_props_author_names', 'false').'
item_props_date='.$this->get_var('item_props_date', 'false').'
item_props_mod_date='.$this->get_var('item_props_mod_date', 'false').'
item_props_pdf_link='.$this->get_var('item_props_pdf_link', 'false').'
item_props_print_link='.$this->get_var('item_props_print_link', 'false').'
item_props_mail_link='.$this->get_var('item_props_mail_link', 'false').'
item_props_language='.$this->get_var('item_props_language', 'false').'
item_props_key='.$this->get_var('item_props_key', 'false').'
item_props_readmore='.$this->get_var('item_props_readmore', 'false').'
item_props_description='.$this->get_var('item_props_description', 'false').'
item_props_keywords='.$this->get_var('item_props_keywords', 'false').'
item_props_robots='.$this->get_var('item_props_robots', 'false').'
item_props_metaauthor='.$this->get_var('item_props_metaauthor', 'false').'
item_props_hideforsuperadmin='.$this->get_var('item_props_hideforsuperadmin', 'false').'
item_new_frontpage='.$this->get_var('item_new_frontpage', 'false').'
item_new_show_title='.$this->get_var('item_new_show_title', 'false').'
item_new_state='.$this->get_var('item_new_state', 'false').'
item_new_access='.$this->get_var('item_new_access', '2').'
item_language='.$this->get_var('item_language', '').'
item_readmore='.$this->get_var('item_readmore', '').'
item_type_select_frontend='.$this->get_var('item_type_select_frontend', 'false').'
item_type_not_text_frontend='.$this->get_var('item_type_not_text_frontend', 'false').'
item_type_not_text_frontend_edit='.$this->get_var('item_type_not_text_frontend_edit', 'false').'
new_item_section_category_select='.$this->get_var('new_item_section_category_select', 'pages').'
image_maxsize='.$this->get_var('image_maxsize', '8000000');
$image_filetypes = $this->get_var('image_filetypes',array(0));
$config .= '
image_filetypes=';
$m = 0;
foreach($image_filetypes as $image_type){
	if($m!=0){
		$config .= ',';		
	}
	$config .= $image_type;
	$m = 1;
}
$config .= '
image_dir=../images/stories/
image_max_width='.$this->get_var('image_max_width', '400').'
image_max_height='.$this->get_var('image_max_height', '500').'
download_allow='.$this->get_var('download_allow', 'false').'
download_filetypes='.$this->get_var('download_filetypes').'
download_maxsize='.$this->get_var('download_maxsize', '8000000').'
download_dir=../media/
download_hits='.$this->get_var('download_hits', 'false').'
download_hitsreset='.$this->get_var('download_hitsreset', 'false').'
download_debugger='.$this->get_var('download_debugger', 'false').'
';
$sections = $this->get_var('sections',array(0));

//if sectionid is not selected, take it out of array
//added the 's' because of the problem with numerical indexes when unsetting in loop
$loops = count($sections);
for($n = 0; $n <= $loops; $n++){
	if(!isset($sections['s'.$n]['sectionid'])){		
		unset ($sections['s'.$n]);					
	} 	
}

//sort array by order
foreach ($sections as $key => $row) {
	$ordersections[$key] = $row['order'];    
}

if(count($sections)!=0){
	array_multisort($ordersections, SORT_ASC, $sections);
}

//write sections array to config string
$config .= 'sections=';
if (is_array($sections)){	
	$counter = 0;
	foreach($sections as $section){
		if($counter!=0){
			$config .= ',';
		}
		$config .= $section[sectionid].';'.$section[sectionname];
		$counter = $counter+1;
	}	
}
$config .= '
inherit_from_parent='.$this->get_var('inherit_from_parent', 'false').'
sections_from_db='.$this->get_var('sections_from_db', 'false').'
inherit_from_parent_move='.$this->get_var('inherit_from_parent_move', 'false').'
child_inherit_from_parent_move='.$this->get_var('child_inherit_from_parent_move', 'false').'
child_inherit_from_parent_change='.$this->get_var('child_inherit_from_parent_change', 'false').'
make_page_alias_unique='.$this->get_var('make_page_alias_unique', 'false').'
truncate_item_title='.intval($this->get_var('truncate_item_title', 0)).'
page_props_publish='.$this->get_var('page_props_publish', 'false').'
page_props_section='.$this->get_var('page_props_section', 'false').'
page_props_alias='.$this->get_var('page_props_alias', 'false').'
page_props_title='.$this->get_var('page_props_title', 'false').'
page_props_title_visible='.$this->get_var('page_props_title_visible', 'false').'
page_props_show_in_menu='.$this->get_var('page_props_show_in_menu', 'false').'
page_props_access='.$this->get_var('page_props_access', 'false').'
page_props_defaulthome='.$this->get_var('page_props_defaulthome', 'false').'
page_props_leading='.$this->get_var('page_props_leading', 'false').'
page_props_nr_intro='.$this->get_var('page_props_nr_intro', 'false').'
page_props_columns='.$this->get_var('page_props_columns', 'false').'
page_props_nr_links='.$this->get_var('page_props_nr_links', 'false').'
page_props_cat_order='.$this->get_var('page_props_cat_order', 'false').'
page_props_primaryorder='.$this->get_var('page_props_primaryorder', 'false').'
page_props_pagination='.$this->get_var('page_props_pagination', 'false').'
page_props_paginationresults='.$this->get_var('page_props_paginationresults', 'false').'
page_props_feedlink='.$this->get_var('page_props_feedlink', 'false').'
page_props_shownoauth='.$this->get_var('page_props_shownoauth', 'false').'
page_props_categorydescription='.$this->get_var('page_props_categorydescription', 'false').'
page_props_categorydescriptionimage='.$this->get_var('page_props_categorydescriptionimage', 'false').'
page_props_categoryname='.$this->get_var('page_props_categoryname', 'false').'
page_props_categorynameclickable='.$this->get_var('page_props_categorynameclickable', 'false').'
page_props_itemtitles='.$this->get_var('page_props_itemtitles', 'false').'
page_props_showintro='.$this->get_var('page_props_showintro', 'false').'
page_props_section_title='.$this->get_var('page_props_section_title', 'false').'
page_props_sectionlink='.$this->get_var('page_props_sectionlink', 'false').'
page_props_linkedtitles='.$this->get_var('page_props_linkedtitles', 'false').'
page_props_readmore='.$this->get_var('page_props_readmore', 'false').'
page_props_itemrating='.$this->get_var('page_props_itemrating', 'false').'
page_props_authornames='.$this->get_var('page_props_authornames', 'false').'
page_props_createdtimedate='.$this->get_var('page_props_createdtimedate', 'false').'
page_props_modifiedtimedate='.$this->get_var('page_props_modifiedtimedate', 'false').'
page_props_showitemnavigation='.$this->get_var('page_props_showitemnavigation', 'false').'
page_props_show_icons='.$this->get_var('page_props_show_icons', 'false').'
page_props_pdf_link='.$this->get_var('page_props_pdf_link', 'false').'
page_props_print='.$this->get_var('page_props_print', 'false').'
page_props_mail_link='.$this->get_var('page_props_mail_link', 'false').'
page_props_showhits='.$this->get_var('page_props_showhits', 'false').'
page_props_feedsummary='.$this->get_var('page_props_feedsummary', 'false').'
page_props_suffix='.$this->get_var('page_props_suffix', 'false').'
page_props_secure='.$this->get_var('page_props_secure', 'false').'
page_props_sectionid='.$this->get_var('page_props_sectionid', 'false').'
page_props_catid='.$this->get_var('page_props_catid', 'false').'
page_props_menuid='.$this->get_var('page_props_menuid', 'false').'
page_props_hideforsuperadmin='.$this->get_var('page_props_hideforsuperadmin', 'false').'
page_new_publish_category='.$this->get_var('page_new_publish_category', 'false').'
page_new_publish_menu='.$this->get_var('page_new_publish_menu', 'false').'
page_new_access_menu='.$this->get_var('page_new_access_menu', '0').'
page_new_access_category='.$this->get_var('page_new_access_category', '0').'
';
//get published itemtypes
$itemtypes = $this->get_var('itemtypes');
$config .= 'itemtypes=';
for($n = 0; $n < count($itemtypes); $n++){
	$row = each($itemtypes);
	if($n!=0){
		$config .= ',';	
	}
	$config .= $row['key'];
	//if itemtype is itemtype plugin, run plugin specific installer script if available
	$item_type = $row['key'];
	if(file_exists(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/itemtypes/'.$item_type.'/'.$item_type.'.php')){
	//exit();
		require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/itemtypes/'.$item_type.'/'.$item_type.'.php');
		$class_name = 'class_itemtype_'.$item_type;	
		$class_itemtype = new $class_name();
		if(method_exists($class_itemtype,'installer')){					
			$class_itemtype->installer();
		}	
	}		
}
$config .= '
START_PAGE_NEW_ATTRIBUTES=';
//page new attribs for this version
$params = $this->get_var('params', '');
$params_string = '';
for($n = 0; $n < count($params); $n++){
	$row = each($params);
	$config .= "\n$row[key]=$row[value]";	
}

	
		//update config		
		$this->db->setQuery( "UPDATE #__pi_config SET config='$config' WHERE id='pi' ");
		$this->db->query();
		
		//redirect
		$sub_task = $this->get_var('sub_task', '');
		if($sub_task=='apply'){
			$url = 'index2.php?option=com_pi_pages_and_items&task=config';
		}else{
			$url = 'index2.php?option=com_pi_pages_and_items';
		}	
		$this->redirect_to_url($url, _pi_lang_configsaved);
	}
	
	function config_itemtype_save(){
		global $item_type;
		
		if(file_exists(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/itemtypes/'.$item_type.'/'.$item_type.'.php')){
			require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/itemtypes/'.$item_type.'/'.$item_type.'.php');
			$class_name = 'class_itemtype_'.$item_type;	
			$class_itemtype = new $class_name();
			if(method_exists($class_itemtype,'config_save')){	
				//only superadministrators have access to config
				if($this->user_type!='Super Administrator'){
					echo "<script> alert('you need to be logged in as a super administrator to edit the pi_Pages-and-Items config.'); window.history.go(-1); </script>";
					exit();
				}		
				$config = $class_itemtype->config_save();
			}	
		}	
		
		//update plugin-specific config	
		if(defined('_JEXEC')){
			//joomla 1.5
			$pluginstable = 'plugins';
		}else{
			//joomla 1.0.x
			$pluginstable = 'mambots';
		}	
		$this->db->setQuery( "UPDATE #__".$pluginstable." SET params='$config' WHERE element='itemtype_".$item_type."' ");
		$this->db->query();	
		
		//redirect
		$sub_task = $this->get_var('sub_task', '');
		if($sub_task=='apply'){
			$url = 'index2.php?option=com_pi_pages_and_items&task=config_itemtype&item_type='.$item_type;
		}else{
			$url = 'index2.php?option=com_pi_pages_and_items&task=config&tab=itemtypes';
		}	
		$this->redirect_to_url($url, _pi_lang_configsaved);
	}
	
	function spunk_up_headers_1_5(){
		if(defined('_JEXEC')){
			//joomla 1.5
			echo '<style type="text/css">
			
			th{	
				text-align: left;
				background: #F0F0F0;
				border-bottom: 1px solid #999999;
			}		
			
			</style>';			
		}
	}
	
	function translate_accesslevel($level){
		if($level==2){
			return _pi_lang_special;
		}else if($level==1){
			return _pi_lang_logged;
		}else{
			return _pi_lang_public;
		}
	}
	
	function get_menutype_title($menutype){	
	//print_r($this->menutypes);echo 'sdfv'; exit;
		/*
		$menutypes = $this->pi_config['menus'];		
		for($n = 0; $n < count($menutypes); $n++){				
			//$row = each($menutypes);
			//if($row[key]==$menutype){
			if($menutypes[$n][0]==$menutype){
				//$menutype_title = $row[value];
				$menutype_title = $menutypes[$n][1];
				break;
			}		
		}
		*/	
		$menutype_title = '';
		$temp_menus = explode(',',$this->pi_config['menus']);		
		for($n = 0; $n < count($temp_menus); $n++){			
			$menutype_temp = explode(';',$temp_menus[$n]);
			if($menutype_temp[0]==$menutype){
				$menutype_title = $menutype_temp[1];
				break;
			}			
		}
		return  strtolower($menutype_title);
	}
	
	/*
	function get_current_menutype_title(){
		$type = $this->current_menutype;
		$floep = $this->get_menutype_title($type);
		$floep = 'soep';
		return $floep;
	}
	*/
	
	//set title. for Joomla 1.0.x this is done with css
	function set_title(){
		if(defined('_JEXEC')){
			//joomla 1.5
			JToolBarHelper::title( JText::_( 'Pages and Items' ), 'content.png' );
		}
	}
	
	function redirect_to_url($url, $message){
		global $mainframe;
		
		if(defined('_JEXEC')){
			//joomla 1.5
			$mainframe->redirect($url, $message);
		}else{
			//joomla 1.0.x
			mosRedirect($url, $message);
		}
	}
	
	function download_delete(){			
		//get fileToDelete
		$file_to_delete = $this->get_var('file_to_delete', '');
		
		$this->db->setQuery("SELECT id, file_name FROM #__pi_downloads WHERE id='$file_to_delete' LIMIT 1");
		$rows = $this->db->loadObjectList();
		$row = $rows[0];
		$id = $row->id;
		$file_name = $row->file_name;
		
		//delete the file
		unlink($this->pi_config['download_dir'].$file_name);
		
		//delete row from database
		$this->db->setQuery("DELETE FROM #__pi_downloads WHERE id='$id'");
		if (!$this->db->query()) {
			echo "<script> alert('".$this->db-> getErrorMsg()."'); window.history.go(-1);</script>\n";
		}
		
		$this->redirect_to_url("index2.php?option=com_pi_pages_and_items&task=download_select&download_deleted=1", _pi_lang_filedeleted);
	}
	
	function download_upload_process(){		
		$new_name = '';
		$error = 0;
		$message = '';
		
		if ($_FILES['file']['name']!=''){
	
			$userfile_name = strtolower($_FILES['file']['name']);			
			$userfile_tmp = $_FILES['file']['tmp_name'];
			$userfile_size = $_FILES['file']['size'];
			//echo 'hier'.$userfile_size;
			if($userfile_size>=($this->pi_config['download_maxsize'])){
				$message = _pi_lang_filetoobig;	
				$error = 1;		
			}
				
			// get extension
			$extension = explode(".", $userfile_name);
			$last = count($extension) - 1;
			$extension = strtolower($extension[$last]);
			
			//check extension				
			$allowed_extensions = explode(" ", $this->pi_config['download_filetypes']);			
			if (!in_array($extension, $allowed_extensions)){
				$message = _pi_lang_wrong_filetype.$this->pi_config['download_filetypes'];	
				$error = 1;	
			}
			
			//rewrite jpeg to jpg
			if($extension=='jpeg'){
				$extension = 'jpg';
			}	
			
			// get the old name of the file	
			$old_name = str_replace('.'.$extension,'',$userfile_name);				
			
			//rename file if already exist
			if(file_exists($this->pi_config['download_dir'].$old_name.'.'.$extension)){			
				$j = 2;
				while (file_exists($this->pi_config['download_dir'].$old_name.'-'.$j.'.'.$extension)){
					$j = $j + 1;
				}
				$new_name = $old_name . "-" . $j;	
			}else{
				$new_name = $old_name;
			}
			
			//replace spaces by underscores
			$new_name = str_replace(' ', '_', $new_name);	
			
			//upload file
			$file_destination = $this->pi_config['download_dir'].$new_name.'.'.$extension;
			if($error==0){	
				if(move_uploaded_file($userfile_tmp, $file_destination)){
					$new_name = $new_name.'.'.$extension;
					
					//store in db
					$access = intval($this->get_var('access', '' ));
					$type= $_FILES['file']['type'];
					$this->db->setQuery( "INSERT INTO #__pi_downloads SET file_name='$new_name', access='$access', type='$type'");
					if (!$this->db->query()) {
						echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>\n";
						exit();
					}
					$new_file_id = $this->db->insertid();
					
					
					$message = $new_name.' '._pi_lang_succes_upload.'&id='.$new_file_id;						           
				}else{		
					$message = _pi_lang_not_upload;			
				}	
			}	        	
					
		}else{
			$message = _pi_lang_no_file;		
		}
		if($message!=''){
			$message = '&message='.$message;
		}	
			
		$this->redirect_to_url('index2.php?option=com_pi_pages_and_items&task=download_upload'.$message);
	}

	function download_access_save(){		
		$access_rights = $this->get_var('access', array(0));
	
		for($n = 0; $n < count($access_rights); $n++){
			$access_row = each($access_rights);		
			$value = $access_row[value];
			$pos = strpos($value, '__');		
			$download_id  = intval(substr($value, 0, $pos));
			$value_length = strlen($value);
			$download_access = intval(substr($value, $pos+2, $value_length));
			$this->db->setQuery( "UPDATE #__pi_downloads SET access='$download_access' WHERE id='$download_id'"	);
			if (!$this->db->query()) {
				echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>\n";
				exit();
			}
		}	
		
		$this->redirect_to_url('index2.php?option=com_pi_pages_and_items&task=download_select', _pi_lang_downloadaccesssaved);
	}

	function download_reset(){		
		$file_to_reset = intval($this->get_var('file_to_reset'));
		
		if($this->pi_config['download_hitsreset'] && $this->pi_config['download_hits']){
			$this->db->setQuery( "UPDATE #__pi_downloads SET hits='0' WHERE id='$file_to_reset'"	);
			if (!$this->db->query()) {
				echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>\n";
				exit();
			}
		}		
		$this->redirect_to_url("index2.php?option=com_pi_pages_and_items&task=download_select", _pi_lang_hitsarereset);
	}
	
	function keep_item_index_clean(){
		
		//get content id's
		$this->db->setQuery( "SELECT id, state "									
		. "FROM #__content "				
		);		
		$items = $this->db->loadObjectList();
		
		//make nice arrays
		$content_ids = array();
		$content_ids_tashed = array();
		foreach($items as $item){
			$content_ids[] = $item->id;
			if($item->state==-2){
				$content_ids_tashed[] = $item->id;
			}
		}	
		
		//get item index data
		$this->db->setQuery( "SELECT id, item_id, itemtype "									
		. "FROM #__pi_item_index "									
		);	
		$index_items = $this->db->loadObjectList();
		
		$from_cit_to_text = array();
		
		//loop through item index data. 
		//delete rows which item in #__content has been deleted and 
		foreach($index_items as $index_item){
			$index_id = $index_item->id;
			$index_item_id = $index_item->item_id;			
			
			$delete_index_row = 0;
			
			//customitemtypes which have been trashed, so delete it from index (makes it a normal item)
			$itemtype = $index_item->itemtype;
						
			if(strpos($itemtype, 'ustom_')){									
				//custom itemtype
				if(in_array($index_item_id, $content_ids_tashed)){
					//trashed
					$delete_index_row = 1;
					//to make it a normal item, take out the custom-itemtype-codes
					$from_cit_to_text[] = $index_item_id;
				}									
			}
			
			//if item is no longer in content table, take it out of index.
			if(!in_array($index_item_id, $content_ids)){									
				$delete_index_row = 1;
				
			}
			
			//delete the index row if needed
			if($delete_index_row){
				$this->db->setQuery("DELETE FROM #__pi_item_index WHERE id='$index_id'");
				$this->db->query();
			}				
		}
		
		/*
		//clean items which where customitemtypes, but have now become normal text-types, from custom itemtype codes
		foreach($from_cit_to_text as $itemid){
			//get item texts			
			$this->db->setQuery( "SELECT introtext, fulltext "									
			."FROM #__content "
			."WHERE id='$itemid' "				
			);		
			$items = $this->db->loadObjectList();
			
			//take the codes out
			foreach($items as $item){		
				echo $item->introtext;
				exit;		
				//$introtext = $this->take_cit_codes_out($item->introtext);
				//$fulltext = $this->take_cit_codes_out($item->fulltext);
			}
			
			//update item
			//$this->db->setQuery( "UPDATE #__content SET introtext='$introtext', fulltext='$fulltext' WHERE id='$itemid'");
			//$this->db->query();			
		}
		*/
	}
	
	function take_cit_codes_out($text){
		$replaceRegex=array();
		$replaceRegex[] = "/{article_id}/is";			
		$replaceRegex[] = "/{article_title}/is";
		$replaceRegex[] = "/{article_created}/is";			
		$replaceRegex[] = "/{article_modified}/is";			
		$replaceRegex[] = "/{article_publish_up}/is";			
		$replaceRegex[] = "/{article_hits}/is";	
		$replaceRegex[] = "/{article_rating}/is";			
		$replaceRegex[] = "/{hide_in_full_view}/is";
		$replaceRegex[] = "/{\/hide_in_full_view}/is";
		$replaceRegex[] = "/{hide_in_intro_view}/is";
		$replaceRegex[] = "/{\/hide_in_intro_view}/is";
		$text = preg_replace($replaceRegex, '', $text);
		return $text;
	}
	
	function include_language(){				
		//get language for plugin, defaults to english
		if (file_exists(dirname(__FILE__).'/language/'.$this->pi_config['language'].'.php')){
			require_once(dirname(__FILE__).'/language/'.$this->pi_config['language'].'.php');				
		}else{
			require_once(dirname(__FILE__).'/language/en.php');
		}
	}	
		
	//section update for menuitems and all underlying menuitems and their items if category blog page is moved
	function section_update_page($section_update_menu_id, $new_section_id){		
		//check if menuitem is content-category-blog, and if so, get cat_id
		$content_category_blog = false;
		if(defined('_JEXEC')){
			//joomla 1.5
			$this->db->setQuery("SELECT link, type FROM #__menu WHERE id='$section_update_menu_id' LIMIT 1");
			$rows = $this->db->loadObjectList();
			$row = $rows[0];
			if((strstr($row->link, 'index.php?option=com_content&view=category&layout=blog') && $row->type!='url')){
				$content_category_blog = true;
				$cat_id = str_replace('index.php?option=com_content&view=category&layout=blog&id=','',$row->link);
			}
		}else{
			//joomla 1.0.x
			$this->db->setQuery("SELECT type, componentid FROM #__menu WHERE id='$section_update_menu_id' LIMIT 1");
			$rows = $this->db->loadObjectList();
			$row = $rows[0];
			if($row->type=='content_blog_category'){
				$content_category_blog = true;
				$cat_id = $row->componentid;
			}
		}			
		
		//only update items on page when its a content_blog_category
		if($content_category_blog){				
			$this->update_items_category($cat_id, $new_section_id);
		}
		
		//update category		
		$this->db->setQuery( "UPDATE #__categories SET section='$new_section_id' WHERE id='$cat_id'");		
		$this->db->query();
		
		//update all underlying child-pages
		if($this->pi_config['child_inherit_from_parent_move']){
			$this->section_update_children($section_update_menu_id, $new_section_id);
		}			
	}	
		
		
	//update section id for underlying pages and all items on them	
	function section_update_children($section_update_page_id, $new_section_id){
		$this->db->setQuery("SELECT id FROM #__menu WHERE parent='$section_update_page_id'"  );
		$rows = $this->db->loadObjectList();
	
		foreach($rows as $row){		
			$this->section_update_page($row->id, $new_section_id);
		}				
	}
	
	//update section for all items on a page (category)	
	function update_items_category($cat_id, $new_section_id){		
		$this->db->setQuery( "UPDATE #__content SET sectionid='$new_section_id' WHERE catid='$cat_id'"	);
		if (!$this->db->query()) {
			echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
			exit();
		}		
	}
	
	function checkUserActionRight($which){		
		//if admin user access component is used
		if($this->pi_config['use_user_access_component'] && $this->user_access_config['active_actions'] && $this->user_type!='Super Administrator'){			
			return $this->class_ua->check_workflow($which, $this->usergroup);	
		}else{
			return true;
		}
	}	
	
	function check_section_access($section_id){		
		//if user access component is used			
		if($this->pi_config['use_user_access_component'] && $this->user_access_config['active_sections'] && $section_id!='' && $this->user_type!='Super Administrator'){						
			return $this->class_ua->check_section_access($section_id, $this->usergroup);					
		}else{
			return true;
		}
	}
	
	function check_useraccess_itemtype($type){		
		//if user access component is used	
		if($this->pi_config['use_user_access_component'] && $this->user_access_config['active_itemtypes'] && $this->user_type!='Super Administrator'){							
			return $this->class_ua->check_useraccess_itemtype($type, $this->usergroup);			
		}else{
			return true;
		}
	}	
	
	function check_item_access($item_id){
		if($this->pi_config['use_user_access_component'] && $this->user_access_config['active_items'] && $this->user_type!='Super Administrator'){
		//if(($this->pi_config['use_user_access_component'] && $this->user_access_config['active_items']) && ((($this->user_type=='Author' || $this->user_type=='Editor' || $this->user_type=='Publisher') && $this->class_ua->pi_ua_config['active_items_frontendusers']) || ($this->user_type=='Manager' || $this->user_type=='Administrator'))){			
			return $this->class_ua->check_item_access($item_id, $this->usergroup);				
		}else{
			return true;
		}		
	}
	
	function check_section_access_by_pageid($page_id){		
		if($this->pi_config['use_user_access_component'] && $this->user_access_config['active_sections'] && $this->user_type!='Super Administrator'){	
			$section_id = $this->pages_sections_array[$page_id];
			$access = false;
			if($this->check_section_access($section_id)){
				$access = true;
			}
		}else{
			$access = true;
		}
		return $access;
	}	
	
	function check_category_access($cat_id){
		//if(($this->pi_config['use_user_access_component'] && $this->user_access_config['active_categories']) && ((($this->user_type=='Author' || $this->user_type=='Editor' || $this->user_type=='Publisher') && $this->class_ua->pi_ua_config['active_categories_frontendusers']) || ($this->user_type=='Manager' || $this->user_type=='Administrator'))){	
		
		if($this->pi_config['use_user_access_component'] && $this->user_access_config['active_categories'] && $this->user_type!='Super Administrator'){			
			return $this->check_category_access2($cat_id, $this->usergroup);				
		}else{
			return true;
		}		
	}
	
	function check_category_access2($cat_id, $usergroup){
		$category_access = $this->get_category_access();			
		$category_right = $cat_id.'__'.$usergroup;		
		if(in_array($category_right, $category_access)){
			return true;
		}else{
			return false;
		}
	}
	
	function get_category_access(){
		$this->db->setQuery("SELECT category_groupid FROM #__pi_aua_categories ");
		return $this->db->loadResultArray();	
	}
	
	function check_page_access($page_id){		
		//if(($this->pi_config['use_user_access_component'] && $this->user_access_config['active_pagesaccess']) && ((($this->user_type=='Author' || $this->user_type=='Editor' || $this->user_type=='Publisher') && $this->user_access_config['active_pagesaccess_frontendusers']) || ($this->user_type=='Manager' || $this->user_type=='Administrator'))){
		if($this->pi_config['use_user_access_component'] && $this->user_access_config['active_pagesaccess'] && $this->user_type!='Super Administrator'){		
			return $this->class_ua->check_page_access($page_id, $this->usergroup);				
		}else{
			return true;
		}		
	}
	
	function check_comp(){
		if($this->pi_config['use_user_access_component'] && $this->user_access_config['use_componentaccess'] && $this->user_type!='Super Administrator'){			
			$this->db->setQuery("SELECT component_usergroupid FROM #__pi_aua_access_components ");			
			if(!in_array('com_pi_pages_and_items__'.$this->usergroup, $this->db->loadResultArray())){				
				if(file_exists(dirname(__FILE__).'/../com_pi_admin_user_access/language/'.$this->user_access_config['language'].'.php')){
					require_once(dirname(__FILE__).'/../com_pi_admin_user_access/language/'.$this->user_access_config['language'].'.php');
				}else{
					require_once(dirname(__FILE__).'/../com_pi_admin_user_access/language/english.php');
				}					
				echo "<script> alert('".addslashes(html_entity_decode(_pi_ua_lang_no_access_component))."'); window.history.go(-1); </script>";
				exit();
			}							
		}		
	}
	
	function config_custom_itemtype_save(){
	
		$type_id = $this->get_var('type_id', '', 'post');
		$plugin = $this->get_var('plugin', '', 'post');
		$name = $this->get_var('name', '');
		$read_more = $this->get_var('read_more', '');
		if(defined('_JEXEC')){
			//joomla 1.5
			$template_intro = addslashes(JRequest::getVar('template_intro','','post','string', JREQUEST_ALLOWRAW));	
			$template_full = addslashes(JRequest::getVar('template_full','','post','string', JREQUEST_ALLOWRAW));	
			$html_after = addslashes(JRequest::getVar('html_after','','post','string', JREQUEST_ALLOWRAW));
			$html_before = addslashes(JRequest::getVar('html_before','','post','string', JREQUEST_ALLOWRAW));
		}else{
			//joomla 1.0.x
			$template_intro = mosGetParam( $_POST, 'template_intro','', _MOS_ALLOWRAW);
			$template_full = mosGetParam( $_POST, 'template_full','', _MOS_ALLOWRAW);
			$html_after = mosGetParam( $_POST, 'html_after','', _MOS_ALLOWRAW);
			$html_before = mosGetParam( $_POST, 'html_before','', _MOS_ALLOWRAW);
		}	
		$editor_id = $this->get_var('editor_id', '');
		$items_are_reordered = $this->get_var('items_are_reordered', '');
		$items_total = $this->get_var('items_total', '');
		
		if(!$type_id){
			//start insert custom itemtype
			
			$this->db->setQuery( "INSERT INTO #__pi_customitemtypes SET name='$name', read_more='$read_more', template_intro='$template_intro', template_full='$template_full', editor_id='$editor_id', html_after='$html_after', html_before='$html_before' ");
			if (!$this->db->query()) {
				echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
				exit();
			}
			
			//get insert id
			$type_id = $this->db->insertid();
			//ADD MS
			//check fields function extended_config_custom_itemtype_save($type_id,$name,'insert',$plugin, $read_more, $template_intro, $template_full, $html_after, $html_before, $editor_id)
			//get fields
			
			//@MS here a new itemtype gets made, so it does not have any fields yet...
			
			$this->db->setQuery( "SELECT id, plugin "
			. "\nFROM #__pi_custom_fields "
			. "\nWHERE type_id='$type_id' "
			);
			$this->db->query();
			$fields = $this->db->loadObjectList();
			foreach($fields as $field)
			{
				if($this->check_field_class_function($field->plugin,'extended_config_custom_itemtype_save'))
				{
					if(in_array($field->plugin, $this->fieldtypes_integrated))
					{
						require_once(dirname(__FILE__).'/class_custom_item_types.php');
						$class_name = 'class_fieldtype_'.$field->plugin;
						$class_object = new $class_name();
						$class_object->extended_config_custom_itemtype_save($type_id,$name,'insert',$field->$plugin, $read_more, $template_intro, $template_full, $html_after, $html_before, $editor_id);
					}
					else
					{
						require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field->plugin.'/'.$field->plugin.'.php');
						$class_name = 'class_fieldtype_'.$field->plugin;
						$class_object = new $class_name();
						$class_object->extended_config_custom_itemtype_save($type_id,$name,'insert',$field->$plugin, $read_more, $template_intro, $template_full, $html_after, $html_before, $editor_id);
					}
				}
			}
			// ADD MS END	
			//end insert custom itemtype
		}else{
			//start update custom itemtype
			
			$this->db->setQuery( "UPDATE #__pi_customitemtypes SET name='$name', read_more='$read_more', template_intro='$template_intro', template_full='$template_full', editor_id='$editor_id', html_after='$html_after', html_before='$html_before' WHERE id='$type_id'");
			if (!$this->db->query()) {
				echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
				exit();
			}
			
			//ADD MS
			//check fields function extended_config_custom_itemtype_save($type_id,$name,'update',$plugin, $read_more, $template_intro, $template_full, $html_after, $html_before, $editor_id)
			$this->db->setQuery( "SELECT id, plugin "
			. "\nFROM #__pi_custom_fields "
			. "\nWHERE type_id='$type_id' "
			);
			$this->db->query();
			$fields = $this->db->loadObjectList();
			foreach($fields as $field)
			{
				if($this->check_field_class_function($field->plugin,'extended_config_custom_itemtype_save'))
				{
					if(in_array($field->plugin, $this->fieldtypes_integrated))
					{
						require_once(dirname(__FILE__).'/class_custom_item_types.php');
						$class_name = 'class_fieldtype_'.$field->plugin;
						$class_object = new $class_name();
						$class_object->extended_config_custom_itemtype_save($type_id,$name,'update',$field->plugin, $read_more, $template_intro, $template_full, $html_after, $html_before, $editor_id);
					}
					else
					{
						require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field->plugin.'/'.$field->plugin.'.php');
						$class_name = 'class_fieldtype_'.$field->plugin;
						$class_object = new $class_name();
						$class_object->extended_config_custom_itemtype_save($type_id,$name,'update',$field->plugin, $read_more, $template_intro, $template_full, $html_after, $html_before, $editor_id);
					}

				}
			}
			// ADD MS END			
			
			//if items where reordered update the ordering of these items	
			if($items_are_reordered==1){											
				for ($n = 1; $n <= $items_total; $n++){		
					$temp_id = intval($this->get_var('reorder_item_id_'.$n, '', 'post'));										
					$this->db->setQuery( "UPDATE #__pi_custom_fields SET ordering='$n' WHERE id='$temp_id'"	);
					if (!$this->db->query()) {
						echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
						exit();
					}					 								
				}
			}
			
			//if choosen to update items by this itemtype in javascript alert on cit config page
			//update items with ajax render script
			if($this->get_var('update_items', false)){			
				$url = 'index3.php?option=com_pi_pages_and_items&task=render_items_by_custom_itemtype&type_id='.$type_id;
				if($this->get_var('sub_task', '')=='apply'){
					$url .= '&futuretask=config_custom_itemtype';
				}else{
					$url .= '&futuretask=config';
				}
				$this->redirect_to_url( $url, '');	
			}
			
			//end update custom itemtype
		}			
		
		//redirect
		$message = _pi_lang_custom_itemtype_saved;		
		if($this->get_var('sub_task', '')=='apply'){
			$url = 'index2.php?option=com_pi_pages_and_items&task=config_custom_itemtype&type_id='.$type_id;
		}else{
			$url = 'index2.php?option=com_pi_pages_and_items&task=config&tab=itemtypes';
		}
		$this->redirect_to_url( $url, $message);				
		
	}
	
	function update_custom_itemtypes_by_type($type_id){
		//update html of all the items of this itemtype		
		$itemtype_name = 'custom_'.$type_id;			
		$this->db->setQuery("SELECT item_id "
		."FROM #__pi_item_index "
		."WHERE itemtype='$itemtype_name' "						
		);
		$items_array = $this->db->loadResultArray();		
		
		foreach($items_array as $item_id){
			$this->update_content_table_from_custom_itemtype($item_id, $itemtype_name);
			//check if the saved item has other_items linked to it, if so, update those			
			$this->update_other_items_if_needed($item_id);
		}	
	}
	
	function config_custom_itemtype_field_save(){
	
		$type_id = $this->get_var('type_id', '');	
		$field_id = $this->get_var('field_id', '');	
		$name = addslashes($this->get_var('name', ''));				
		$plugin = $this->get_var('plugin', '');	
		
		//get params
		$field_params = $this->get_var('field_params', '');	
		//if(count($field_params)==1){
			//$params_string = $field_params;
		//}else{
		$params_string = '';
		for($n = 0; $n < count($field_params); $n++){
			$row = each($field_params);			
			$params_string .= "$row[key]-=-$row[value][;-)# ]";
		}
		//}
			
		
		//get fieldtype class
		$class_name = 'class_fieldtype_'.$plugin;
		$this->include_field_class($plugin);	
		$class_plugin = new $class_name();
		
		//if there is a special function for the fieldtype when saving the config, do that
		if(method_exists($class_plugin, 'params_save')){		
			$params_string = $class_plugin->params_save($params_string);
		}
		
		$params_string = addslashes($params_string);			
			
		if($field_id==''){
			//new field	
					
			//reorder fields to keep things tidy
			$ordering = $this->reorder_fields($type_id);
			
			$this->db->setQuery( "INSERT INTO #__pi_custom_fields SET name='$name', type_id='$type_id', plugin='$plugin', ordering='$ordering', params='$params_string'");
			if (!$this->db->query()) {
				echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
				exit();
			}
			
			//get insert id
			$field_id = $this->db->insertid();	
			
			//insert value-rows with the default value for each item using this	field
			$itemtype_name = 'custom_'.$type_id;			
			$this->db->setQuery("SELECT item_id "
			."FROM #__pi_item_index "
			."WHERE itemtype='$itemtype_name' "						
			);
			$items_array = $this->db->loadResultArray();	
				
			$default_value = $this->get_field_param($params_string, 'default_value');
			
			//check if we need to work on the default value (render it as a parameter or so, see example fieldtype link)				
			if(method_exists($class_plugin, 'default_value')){		
				$default_value = $class_plugin->default_value($default_value);
			}
			
			foreach($items_array as $item_id){
				
				$this->db->setQuery( "INSERT INTO #__pi_custom_fields_values SET field_id='$field_id', item_id='$item_id', value='$default_value' ");
				$this->db->query();
				
			}
			
			//ADD MS 
			// check fields function extended_config_custom_itemtype_field_save($type_id,$field_id,$name,$plugin,'insert',$default_value)
			//TODO loop 
			$this->db->setQuery("SELECT * FROM #__pi_custom_fields WHERE type_id='$type_id' ");
			$this->db->query();
			$rows = $this->db->loadObjectList();
			foreach($rows as $row)
			{
				if($this->check_field_class_function($row->plugin,'extended_config_custom_itemtype_field_save'))
				{
					if(in_array($row->plugin, $this->fieldtypes_integrated))
					{
						require_once(dirname(__FILE__).'/class_custom_item_types.php');
						$class_name = 'class_fieldtype_'.$row->plugin;
						$class_object = new $class_name();
						$class_object->extended_config_custom_itemtype_field_save($type_id,$field_id,$name,$plugin,'insert',$default_value);
					}
					else
					{
						require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$row->plugin.'/'.$row->plugin.'.php');
						$class_name = 'class_fieldtype_'.$row->plugin;
						$class_object = new $class_name();
						$class_object->extended_config_custom_itemtype_field_save($type_id,$field_id,$name,$plugin,'insert',$default_value);
					}
				}
			}
			//ADD MS END		
		
		}else{
			//edit field
			$this->db->setQuery( "UPDATE #__pi_custom_fields SET name='$name', params='$params_string' WHERE id='$field_id'"	);
			if (!$this->db->query()) {
				echo "<script> alert('".$this->db->getErrorMsg()."'); window.history.go(-1); </script>";
				exit();
			}
			
			//ADD MS
			// check fields function extended_config_custom_itemtype_field_save($type_id,$field_id,$name,$plugin,'insert',$default_value)
			$this->db->setQuery("SELECT * FROM #__pi_custom_fields WHERE type_id='$type_id' ");
			$this->db->query();
			$rows = $this->db->loadObjectList();
			foreach($rows as $row)
			{
				if($this->check_field_class_function($row->plugin,'extended_config_custom_itemtype_field_save'))
				{
					$default_value = '';
					if(in_array($row->plugin, $this->fieldtypes_integrated))
					{
						require_once(dirname(__FILE__).'/class_custom_item_types.php');
						$class_name = 'class_fieldtype_'.$row->plugin;
						$class_object = new $class_name();
						$class_object->extended_config_custom_itemtype_field_save($type_id,$field_id,$name,$plugin,'update',$default_value);
					}
					else
					{
						require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$row->plugin.'/'.$row->plugin.'.php');
						$class_name = 'class_fieldtype_'.$row->plugin;
						$class_object = new $class_name();
						$class_object->extended_config_custom_itemtype_field_save($type_id,$field_id,$name,$plugin,'update',$default_value);
					}
				}
			}
			//ADD MS END
			
		}	
		
		//if choosen to update items by this itemtype in javascript alert on field config page
		//update items with ajax render script
		if($this->get_var('update_items', false)){			
			//update all items of this type
			$url = 'index3.php?option=com_pi_pages_and_items&task=render_items_by_custom_itemtype&type_id='.$type_id;
			if($this->get_var('sub_task', '')=='apply'){
				$url .= '&futuretask=config_custom_itemtype_field&field_id='.$field_id;
			}else{
				$url .= '&futuretask=config_custom_itemtype&from=field';
			}
			$this->redirect_to_url( $url, '');		
		}else{		
			//redirect without updateing items			
			$message = _pi_lang_field_saved;
			if($this->get_var('sub_task', '')=='apply'){			
				$url = 'index2.php?option=com_pi_pages_and_items&task=config_custom_itemtype_field&field_id='.$field_id;
			}else{
				$url = 'index2.php?option=com_pi_pages_and_items&task=config_custom_itemtype&type_id='.$type_id;
			}
			$this->redirect_to_url( $url, $message);		
		}
		
	}
	
	function make_value_into_parameter($parameter, $value){
		return $parameter.'-=-'.$value.'[;-)# ]';
	}
	
	function custom_itemtype_fields_delete(){	
		$fields_to_delete = $this->get_var('items_to_delete', array(0));
		$type_id = 	$this->get_var('type_id','');
		
		//ADD MS
		// check fields function extended_config_custom_itemtype_field_delete($type_id,$fields_to_delete) return $fields_to_delete
		$this->db->setQuery("SELECT * FROM #__pi_custom_fields WHERE type_id='$type_id'");
		$this->db->query();
		$rows = $this->db->loadObjectList();
		foreach($rows as $field)
		{
			if($this->check_field_class_function($field->plugin,'extended_config_custom_itemtype_field_delete'))
			{
				if(in_array($field->plugin, $this->fieldtypes_integrated))
				{
					require_once(dirname(__FILE__).'/class_custom_item_types.php');
					$class_name = 'class_fieldtype_'.$field->plugin;
					$class_object = new $class_name();
					$xfields_to_delete = $class_object->extended_config_custom_itemtype_field_delete($type_id,$fields_to_delete);					
				}
				else
				{
					require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field->plugin.'/'.$field->plugin.'.php');
					$class_name = 'class_fieldtype_'.$field->plugin;
					$class_object= new $class_name();
					$xfields_to_delete = $class_object->extended_config_custom_itemtype_field_delete($type_id,$fields_to_delete);					
				}
			}			
		}
		//END ADD MS
		
		for($n = 0; $n < count($fields_to_delete); $n++){
			$row = each($fields_to_delete);
			if($row['value']==true){				
				$id = $row['value'];
				
				//do pre-delete field-values event (axample: delete images before the image field is deleted)
				$this->db->setQuery("SELECT * FROM #__pi_custom_fields WHERE id='$id'");
				$this->db->query();
				$fields = $this->db->loadObjectList();
				foreach($fields as $field){					
					//check if the fieldtype has a function for when the item is deleted, if so, do the function
					if(in_array($field->plugin, $this->fieldtypes_integrated)){
						require_once(dirname(__FILE__).'/class_custom_item_types.php');
						$class_name = 'class_fieldtype_'.$field->plugin;
						$class_object = new $class_name();						
						if(method_exists($class_object, 'field_delete')){												
							$class_object->field_delete($field);
						}
					}else{
						require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field->plugin.'/'.$field->plugin.'.php');
						$class_name = 'class_fieldtype_'.$field->plugin;
						$class_object = new $class_name();	
						if(method_exists($class_object, 'field_delete')){								
							$class_object->field_delete($field);
						}
					}
				}						
				
				//delete field
				$this->db->setQuery("DELETE FROM #__pi_custom_fields WHERE id='$id'");
				$this->db->query();	
				
				//delete field values
				$this->delete_fields_values($id);		
			}		
		}
		
		//update items output
		//$this->update_custom_itemtypes_by_type($type_id);
		
		//update items with ajax render script and return to cit-config-page			
		$url = 'index3.php?option=com_pi_pages_and_items&task=render_items_by_custom_itemtype&type_id='.$type_id;		
		$url .= '&futuretask=config_custom_itemtype';		
		$this->redirect_to_url( $url, '');		
		
	}
	
	function delete_fields_values($field_id){		
		//delete field values
		$this->db->setQuery("DELETE FROM #__pi_custom_fields_values WHERE field_id='$field_id'");
		$this->db->query();
	}
	
	function reorder_fields($type_id){				
		$this->db->setQuery("SELECT id FROM #__pi_custom_fields WHERE type_id='$type_id' ORDER BY ordering ASC"  );
		$rows = $this->db->loadObjectList();
		$counter = 1;
		foreach($rows as $row){	
			$id = $row->id;
			$this->db->setQuery( "UPDATE #__pi_custom_fields SET ordering='$counter' WHERE id='$id'");
			$this->db->query();
			$counter = $counter + 1;				
		}
		return $counter;
	}
	
	function get_installed_fieldtypes(){
		$dir_itemtypes = array();
		
		//make an array from installed fieldtypes						
		if( defined('_JEXEC') ){
			//joomla 1.5
			jimport( 'joomla.filesystem.folder');
			if(file_exists(dirname(__FILE__).'/../../../plugins/pages_and_items/fieldtypes')){
				$dir_itemtypes = JFolder::folders(dirname(__FILE__).'/../../../plugins/pages_and_items/fieldtypes/');
			}
		}else{
			//joomla 1.0.x	
			if(file_exists(dirname(__FILE__).'/../../../mambots/pages_and_items/fieldtypes')){						
				$dir_itemtypes = mosReadDirectory(dirname(__FILE__).'/../../../mambots/pages_and_items/fieldtypes/');
			}
		}	
													
		$installed_fieldtypes = $this->fieldtypes_integrated;	
										
		foreach($dir_itemtypes as $itemtype){
			array_push($installed_fieldtypes, $itemtype);	
		}
		
		//sort fieltypes alfabetical		
		$column = '';//reset column if you used this elsewhere
		foreach($installed_fieldtypes as $fieldtype){
			$column[] = $fieldtype[0];	
		}
		$sort_order = SORT_ASC;//define as a var or else ioncube goes mad
		array_multisort($column, $sort_order, $installed_fieldtypes);
			
		return $installed_fieldtypes;
	}
	
	function config_custom_itemtype_delete(){
		$type_id = $this->get_var('type_id');
		$type_name = 'custom_'.$type_id;
		$delete_items = $this->get_var('delete_items', false);
		
		//get item-ids		
		$this->db->setQuery("SELECT item_id "														
		. "\nFROM #__pi_item_index "									
		. "\nWHERE itemtype='$type_name' "
		);
		$item_ids_array = $this->db->loadResultArray();
		
		
		
		//ADD MS
		// check fields function extended_config_custom_itemtype_delete($type_id,$fields) 
		// we can make an redirect in the $class_object->extended_config_custom_itemtype_delete function
		// if we do not want that the custom_itemtype are deleted
		//$this->db->setQuery("SELECT * FROM #__pi_custom_fields WHERE type_id='$type_id' LIMIT 1 ");
		//why limit ?
		$this->db->setQuery("SELECT * FROM #__pi_custom_fields WHERE type_id='$type_id' ");
		$this->db->query();
		$rows = $this->db->loadObjectList();
		
		$done = 0;
		foreach($rows as $field)
		{
			if(!$done){
				if($this->check_field_class_function($field->plugin,'extended_config_custom_itemtype_delete'))
				{
					if(in_array($field->plugin, $this->fieldtypes_integrated))
					{
						require_once(dirname(__FILE__).'/class_custom_item_types.php');
						$class_name = 'class_fieldtype_'.$field->plugin;
						$class_object = new $class_name();
						$class_object->extended_config_custom_itemtype_delete($type_id,$rows);					
					}
					else
					{
						require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field->plugin.'/'.$field->plugin.'.php');
						$class_name = 'class_fieldtype_'.$field->plugin;
						$class_object = new $class_name();
						$class_object->extended_config_custom_itemtype_delete($type_id,$rows);					
					}
				}
			}	
			$done = 1;					
			
		}
		//END ADD MS
		
		foreach($rows as $field){
			if($delete_items){																		
				//check if the fieldtype has a function for when the item is deleted, if so, do the function
				if(in_array($field->plugin, $this->fieldtypes_integrated)){
					
					require_once(dirname(__FILE__).'/class_custom_item_types.php');
					$class_name = 'class_fieldtype_'.$field->plugin;
					$class_object = new $class_name();						
					if(method_exists($class_object, 'item_delete')){
						for($n = 0; $n < count($item_ids_array); $n++){	
																
							$class_object->item_delete($item_ids_array[$n], $type_id, $field);									
						}		
					}
				}else{
					require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field->plugin.'/'.$field->plugin.'.php');
					$class_name = 'class_fieldtype_'.$field->plugin;
					$class_object = new $class_name();	
					if(method_exists($class_object, 'item_delete')){
						for($n = 0; $n < count($item_ids_array); $n++){											
							$class_object->item_delete($item_ids_array[$n], $type_id, $field);
						}
					}
				}			
			}
		}	
			
		//get field-ids
		$this->db->setQuery( "SELECT id "														
		. "\nFROM #__pi_custom_fields "									
		. "\nWHERE type_id='$type_id' "
		);
		$fields = $this->db->loadResultArray();
		
		$fields = implode(',', $fields);		
		
		//delete values
		$this->db->setQuery("DELETE FROM #__pi_custom_fields_values WHERE field_id IN ($fields) ");
		$this->db->query();	
		
		//delete fields		
		$this->db->setQuery("DELETE FROM #__pi_custom_fields WHERE type_id='$type_id'");
		$this->db->query();	
		
		//delete type		
		$this->db->setQuery("DELETE FROM #__pi_customitemtypes WHERE id='$type_id'");
		$this->db->query();		
		
		$item_ids = implode(',', $item_ids_array);
		
		//do we need to delete all items as well?		
		if($delete_items){		
			//delete items		
			$this->db->setQuery("DELETE FROM #__content WHERE id IN ($item_ids) ");
			$this->db->query();
			
			//delete item from index		
			$this->db->setQuery("DELETE FROM #__pi_item_index WHERE itemtype='$type_name' ");
			$this->db->query();	
		}else{		
			//no deleting items, but to make them edittable as normal content, set itemtype to 'text' in itemtype-index
			foreach($item_ids_array as $item_id){
				$this->db->setQuery("UPDATE #__pi_item_index SET itemtype='text' WHERE item_id='$item_id' ");
				$this->db->query();	
			}
		}		
		
		//take itemtype out of config in case it was published
		$this->take_itemtype_out_of_configuration($type_name);			
			
		//redirect
		$url = 'index2.php?option=com_pi_pages_and_items&task=config&tab=itemtypes';
		$this->redirect_to_url( $url, _pi_lang_itemtype_deleted);
	}
	
	function take_itemtype_out_of_configuration($itemtype){			

		$this->db->setQuery("SELECT config "
		."FROM #__pi_config "
		."WHERE id='pi' "
		."LIMIT 1"
		);
		$temp = $this->db->loadObjectList();
		$temp = $temp[0];
		$config_string = $temp->config;	
		
		$start_itemtypes = strpos($config_string, 'itemtypes=');
		$end_itemtypes = strpos($config_string, 'START_PAGE_NEW_ATTRIBUTES');
		$config_before = substr($config_string, 0, $start_itemtypes);
		$config_after = substr($config_string, $end_itemtypes, 999999);	
		
		//make new config string
		$config = $config_before.'itemtypes=';	
		$first = true;	
		for($n = 0; $n < count($this->itemtypes); $n++){
			if($this->itemtypes[$n] != $itemtype){
				if($first==false){
					$config .= ',';
				}			
				$config .= $this->itemtypes[$n];
				$first = false;
			}
		}		
		$config .= '
		'.$config_after;		
			
		//update config		
		$this->db->setQuery( "UPDATE #__pi_config SET config='$config' WHERE id='pi' ");
		$this->db->query();
	}	
	
	function get_categories(){
		static $pi_category_array;
		
		if(!$pi_category_array){
			$this->db->setQuery("SELECT id, title, section "
			."FROM #__categories "			
			);
			$pi_categories_object = $this->db->loadObjectList();
			
			$pi_category_array = array();
			foreach($pi_categories_object as $category){
				$pi_category_array[] = array($category->id, $category->title, $category->section);
			}
		}
		return $pi_category_array;
	}
	
	function get_sections(){
		static $pi_sections_array;
		
		if(!$pi_sections_array){
			$this->db->setQuery("SELECT id, title "
			."FROM #__sections "			
			);
			$pi_sections_object = $this->db->loadObjectList();
			
			$pi_sections_array = array();
			foreach($pi_sections_object as $pi_section){
				$pi_sections_array[] = array($pi_section->id, $pi_section->title);
			}
		}
		return $pi_sections_array;
	}
	

	//CHANGE MS NOVEMBER 2010
	//function update_content_table_from_custom_itemtype($item_id, $item_type,$new_item=false){
	function update_content_table_from_custom_itemtype($item_id, $item_type,$new_item=false,$row = false, $fields = false, $into=false){
		
		//get type_id
		$pos = strpos($item_type, 'ustom_');
		$type_id = substr($item_type, $pos+6, strlen($item_type));	
				
		//get template						
		$this->db->setQuery( "SELECT template_intro, template_full, read_more, editor_id, html_after, html_before "
		. "\nFROM #__pi_customitemtypes "		
		. "\nWHERE id='$type_id' "
		. "\nLIMIT 1 "
		);
		$templates = $this->db->loadObjectList();
		$template = $templates[0];
		$template_intro = $template->template_intro;
		$template_full = $template->template_full;	
		$read_more = $template->read_more;	
		$editor_id = $template->editor_id;
		$html_after = $template->html_after;
		$html_before = $template->html_before;
		
		//CHANGE MS NOVEMBER 2010
		if(!$row)
		{
			//get item
			$this->db->setQuery( "SELECT * "
			. "\nFROM #__content "		
			. "\nWHERE id='$item_id' "
			. "\nLIMIT 1 "
			);
			$items = $this->db->loadObjectList();
			$row = $items[0];
		}
		if(!$fields)
		{
			//get fields and values
			$this->db->setQuery( "SELECT f.*, v.*, v.id AS value_id, f.id AS field_id "
			. "\n FROM #__pi_custom_fields_values AS v "
			. "\n LEFT JOIN #__pi_custom_fields AS f "	
			. "\n ON f.id=v.field_id "
			. "\n WHERE f.type_id='$type_id' "	
			. "\n AND v.item_id='$item_id' "			
			. "\n ORDER BY f.ordering ASC "
			);			
			$fields = $this->db->loadObjectList();		
		}
		//END CHANGE MS NOVEMBER 2010	
		
		/*
		if($read_more=='3'){
			$introtext = $this->render_html_from_custom_itemtype_template($template_intro, $fields, $row, 'intro', 3, $editor_id,  $html_after, $html_before );
		}else{
			$introtext = $this->render_html_from_custom_itemtype_template($template_intro, $fields, $row, 'intro');
		}
		*/
		$introtext = $this->render_html_from_custom_itemtype_template($template_intro, $fields, $row, 'intro', $read_more, $editor_id,  $html_after, $html_before);		
		//exit;
		if($read_more=='1'){
			//no readmore
			$fulltext = '';
		}elseif($read_more=='2'){
			//only read more if not empty
			$fulltext_temp = $this->render_html_from_custom_itemtype_template($template_full, $fields, $row, 'full');
			$fulltext_temp2 = str_replace(' ','',$fulltext_temp);
			$length_with_content = strlen($fulltext_temp2);
			
			$full_template_temp = $template_full;
			$template_array = explode('{field_',$full_template_temp);
			foreach($template_array as $template_chunk){
				if(strpos($template_chunk,'}')){
					$end_tag = strpos($template_chunk,'}');					
					$temp = substr($template_chunk, 0, $end_tag);					
					$underscore = strpos($temp,'_');
					$field_id = substr($temp, $underscore+1, strlen($temp));									
					$the_rest = substr($template_chunk, $end_tag+1, strlen($template_chunk));					
					$full_template_temp2 .= $the_rest;					
				}else{
					$full_template_temp2 .= $template_chunk;
				}				
			}
			
			$full_template_temp2 = str_replace(' ','',$full_template_temp2);
			$length_without_content = strlen($full_template_temp2);
			
			//if($length_with_content==$length_without_content){
			if($length_with_content==$length_without_content || $length_without_content==0){
				//there is no content in fulltext 
				$fulltext = '';				
			}else{
				//there is content in fulltext				
				$fulltext = $this->render_html_from_custom_itemtype_template($template_full, $fields, $row, 'full', $read_more);				
			}
		}elseif($read_more=='3'){
			//readmore using read-more button in one editor
			$fulltext = $this->render_html_from_custom_itemtype_template($template_full, $fields, $row, 'full', $read_more, $editor_id,  $html_after, $html_before );
		}else{
			//normal read more			
			$fulltext = $this->render_html_from_custom_itemtype_template($template_full, $fields, $row, 'full', $read_more);
		}
		
		//CHANGE MS NOVEMBER 2010
		if(!$into){
			//update item for read_more link
			$this->db->setQuery( "UPDATE #__content SET introtext='$introtext', `fulltext`='$fulltext' WHERE id='$item_id' ");
			if (!$this->db->query()) {
				echo $this->db->getErrorMsg();
				exit();
			}
		}else{
			return array("introtext"=>$introtext,"fulltext"=>$fulltext);
		}
		//END CHANGE MS NOVEMBER 2010	
		
		
		//ADD MS 18.09.2009
//		$fields = $this->db->loadObjectList();
		if(!$new_item && !$into){
			$this->db->setQuery( "SELECT * "
			."\nFROM #__pi_custom_fields "
			."\nWHERE type_id='$type_id' "																							
			);
			$fields = $this->db->loadObjectList();
			/*//get data-fields
			$this->db->setQuery( "SELECT id, field_id "														
			. "\nFROM #__pi_custom_fields_values "									
			. "\nWHERE item_id='$item_id' "																								
			);
			$data_fields = $this->db->loadObjectList();					
			//make array of fields which have a data field and make fields-datafields array	
			$new_cit = true;
			$fields_datafields_array = array();
			foreach($fields as $field){	
				foreach($data_fields as $field_data){
					if($field_data->field_id==$field->id){							
						$fields_datafields_array[$field_data->field_id] = $field_data->id;
						$new_cit = false;							
						break;
					}						
				}
			}*/
			
			foreach($fields as $field)
			{
				//start update	
				//if field-class got a special special function for saving do that	
				if($this->check_field_class_function($field->plugin,'extended_save_custom_itemtype_field_save'))
				{
					//$field->id = $field->field_id;
					if(in_array($field->plugin, $this->fieldtypes_integrated))
					{
						require_once(dirname(__FILE__).'/class_custom_item_types.php');
						$class_name = 'class_fieldtype_'.$field->plugin;
						$class_object = new $class_name();
						$class_object->extended_save_custom_itemtype_field_save($field, 'update',$item_id,$type_id,$fields);
					}
					else
					{
						require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field->plugin.'/'.$field->plugin.'.php');
						$class_name = 'class_fieldtype_'.$field->plugin;
						$class_object = new $class_name();
						$class_object->extended_save_custom_itemtype_field_save($field, 'update',$item_id,$type_id,$fields);
					}
				}
			}
		}
		//end field loop MS
		//ADD MS 18.09.2009 END
		
	}
	
	/*
	function render_html_from_custom_itemtype_template($template, $fields, $row, $intro_or_full, $readmore_type=0, $editor_id=0,  $html_after='', $html_before='' ){
			
		$read_more_link_defined = $this->check_for_read_more_link($fields, $editor_id);	
		
		//no template specified, so render default template		
		if(!$template){							
			//ADD MS
			$template_special = false;
			foreach($fields as $field)
			{
				if($this->check_field_class_function($field->plugin,'template_special_output'))
				{
					if(in_array($field->plugin, $this->fieldtypes_integrated))
					{
						require_once(dirname(__FILE__).'/class_custom_item_types.php');
						$class_name = 'class_fieldtype_'.$field->plugin;
						$class_object = new $class_name();
						$template .= $class_object->template_special_output($fields);
					}
					else
					{
						require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field->plugin.'/'.$field->plugin.'.php');
						$class_name = 'class_fieldtype_'.$field->plugin;
						$class_object = new $class_name();
						$template .= $class_object->template_special_output($fields);
					}
					$template_special = true;
				}
			}
			
			//if(!$template_spezial)
			if(!$template)
			{
			//END ADD MS
				foreach($fields as $field)
				{
					$template .= '<div>';
					//$template .= '{field_'.$field->plugin.'_'.$field->field_id.'}';
					$template .= '{field_'.$field->name.'_'.$field->field_id.'}';
					$template .= '</div>';
				}
			//ADD MS
			}
			//END ADD MS				
		}			
			
		$regex = "/{field_(.*?)_(.*?)}/is";
		preg_match_all($regex, $template, $matches); 	
		
		$fields_array = array();		
		//redo array to take template properties out
		//split second match into field_id and properties
		for($n = 0; $n < count($matches[2]); $n++){	
			$temp_tag = $matches[0][$n];
			$temp = $matches[2][$n];						
			if(strpos($temp,' ')){
				//fieldtag got a space, so properties could be defined like so:
				//{field_image_27 display=thumb soup=chicken}
				$template_params = explode(' ',$matches[0][$n]);
				$rest_of_fieldtag = explode('_',$template_params[0]);
				$reversed_rest_of_fieldtag = array_reverse($rest_of_fieldtag);
				$temp_field_id = $reversed_rest_of_fieldtag[0];
				//work on string to get only the properties
				$temp_field_properties = str_replace($temp_field_id.' ','',$matches[2][$n]);				
			}else{
				$temp_field_id = $matches[2][$n];
				$temp_field_properties = '';
			}
			$fields_array[] = array($temp_tag, $temp_field_id, $temp_field_properties);
		}		
		$html = addslashes($template);			
		
		//don't show any fields in full item view which are before the editor if a readmore is defined and readmore is set to editor
		if($readmore_type=='3' && $intro_or_full=='full' && $read_more_link_defined){
			for($n = 0; $n < count($fields_array); $n++){
				if($fields_array[$n][1]==$editor_id){
					$editor_tag = $fields_array[$n][0];						
					$length = strlen($html);
					$pos = strpos($html, $editor_tag);
					$html = substr($html, $pos, $length);	
					$html = $html_before.$html;					
				}
			}				
		}
		
		//don't show any fields in intro view which are after the editor if a readmore is defined and readmore is set to editor
		if($readmore_type==3 && $intro_or_full=='intro' && $read_more_link_defined){
			for($n = 0; $n < count($fields_array); $n++){
				if($fields_array[$n][1]==$editor_id){
					$editor_tag = $fields_array[$n][0];						
					$length = strlen($editor_tag);
					$pos = strpos($html, $editor_tag);						
					$html = substr($html, 0, ($pos+$length));
					$html = $html.$html_after;						
				}
			}						
		}
		
		//if full item, readmore is not defined, cit config specified editor, no fullitem html, so no readmore link
		if($readmore_type==3 && $intro_or_full=='full' && !$read_more_link_defined){
			$html = '';				
		}
		
		//get all matches on what is left of the template
		preg_match_all($regex, $html, $matches);		
		
		for($n = 0; $n < count($fields_array); $n++){		
			foreach($fields as $field){
				if($field->field_id==$fields_array[$n][1]){
					$field_tag = $fields_array[$n][0];
					
					$field->template_properties = $fields_array[$n][2];					
					
					//get output for field										
					$temp = $this->get_custom_itemtype_field_content($field, $intro_or_full, $readmore_type, $editor_id);
					$html = str_replace($field_tag, $temp, $html);
				}					
			}
		}
					
		return $html;		
	}
	*/
function render_html_from_custom_itemtype_template($template, $fields, $row, $intro_or_full, $readmore_type=0, $editor_id=0,  $html_after='', $html_before='' ){
	
		$read_more_link_defined = $this->check_for_read_more_link($fields, $editor_id);
				
		//no template specified, so render default template		
		if(!$template){							
			//ADD MS
			$template_special = false;
			foreach($fields as $field)
			{
				if($this->check_field_class_function($field->plugin,'template_special_output'))
				{
					if(in_array($field->plugin, $this->fieldtypes_integrated))
					{
						require_once(dirname(__FILE__).'/class_custom_item_types.php');
						$class_name = 'class_fieldtype_'.$field->plugin;
						$class_object = new $class_name();
						$template .= $class_object->template_special_output($fields);
					}
					else
					{
						require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field->plugin.'/'.$field->plugin.'.php');
						$class_name = 'class_fieldtype_'.$field->plugin;
						$class_object = new $class_name();
						$template .= $class_object->template_special_output($fields);
					}
					$template_special = true;
				}
			}
			
			//if(!$template_spezial)
			if(!$template)
			{
			//END ADD MS
				foreach($fields as $field)
				{
					$template .= '<div>';
					//$template .= '{field_'.$field->plugin.'_'.$field->field_id.'}';
					$template .= '{field_'.$field->name.'_'.$field->field_id.'}';
					$template .= '</div>';
				}
			//ADD MS
			}
		}
		
		$html = addslashes($template);
		//Deal with readmore type 3
		if($readmore_type=='3')
		{
			if($read_more_link_defined)
			{
				$editor_tag="";
				//Find editor_tag - brute force becase we do not know field name for editor!!
				foreach($fields as $field)
				{
					if ($field->field_id == $editor_id)
					{
						// CHANGE MS 09.09.2009
						//$editor_tag='{field_'.$field->name.'_'.$field->field_id.'}';
						$editor_tag='\{field_'.$field->name.'_'.$field->field_id.'\}';
						break;
					}
				}
				//ADD MS 09.09.2009
				foreach($fields as $field)
				{
					if($this->check_field_class_function($field->plugin,'extended_editor_tag'))
					{
						if(in_array($field->plugin, $this->fieldtypes_integrated))
						{
							require_once(dirname(__FILE__).'/class_custom_item_types.php');
							$class_name = 'class_fieldtype_'.$field->plugin;
							$class_object = new $class_name();
							$ex_editor_tag = $class_object->extended_editor_tag($fields,$editor_id,$intro_or_full);
						}
						else
						{
							require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$field->plugin.'/'.$field->plugin.'.php');
							$class_name = 'class_fieldtype_'.$field->plugin;
							$class_object = new $class_name();
							$ex_editor_tag = $class_object->extended_editor_tag($fields,$editor_id,$intro_or_full);
						}
						if (isset($ex_editor_tag))
						{
							
							$editor_tag = $ex_editor_tag;
							//ADDED MS 09.09.2009 16:30
							$html=stripslashes($html);
							break;
						}
					}
				}
				//ADD MS END 09.09.2009
				if (! empty($editor_tag))
				{
					switch($intro_or_full){
					case 'intro':
						// in intro view, delete everything after the editor (leave editor)
						//CHANGE MS 09.09.2009 16:30
						//$html=preg_replace('/'.$editor_tag.'(.*?)/is',$editor_tag,$html).$html_after;
						//CHANGE MS 10.09.2009 11:00 add div is </div> after $editor_tag
						//$html=preg_replace('/'.$editor_tag.'.*/is',stripslashes($editor_tag'),$html).$html_after;
						//$html=preg_replace('/'.$editor_tag.'(<\/div>{0,1}).*/is',stripslashes($editor_tag.'${1}'),$html).$html_after;
						preg_match('/'.$editor_tag.'(<\/div>?).*/is', $html, $matches);
						if($matches)
						{
							$html=preg_replace('/'.$editor_tag.'(<\/div>{0,1}).*/is',stripslashes($editor_tag.'${1}'),$html).$html_after;
						}
						else
						{
							$html=preg_replace('/'.$editor_tag.'.*/is',stripslashes($editor_tag),$html).$html_after;
						}

						break;
					case 'full':
						// in full view, delete everything before the editor (leave editor)
						//CHANGE MS 09.09.2009
						//$html=$html_before.preg_replace('/(.*?)'.$editor_tag.'/is',$editor_tag,$html);
						//CHANGE MS 10.09.2009 11:00 add </div> is <div> before $editor_tag
						//$html=$html_before.preg_replace('/(.*?)'.$editor_tag.'/is',stripslashes($editor_tag),$html);
						preg_match('/(<\/div>?)'.$editor_tag.'.*/is', $html, $matches);
						if($matches)
						{
							$html=$html_before.preg_replace('/(.*?)(<div>?)'.$editor_tag.'/is',stripslashes('${2}'.$editor_tag),$html);
						}
						else
						{
							$html=$html_before.preg_replace('/(.*?)'.$editor_tag.'/is',stripslashes($editor_tag),$html);
						}
						//check <div>
						break;
					default;
						break;
					}
				}
			}else{
				if ($intro_or_full=='full'){
					$html='';
				}
			}
		}
		
		$replaceRegex=array();
		$replaceValue=array();
		if (! empty($row)){
			$replaceRegex[]='/{article_id}/is';
			$replaceValue[]=$row->id;
			$replaceRegex[]='/{article_title}/is';
			$replaceValue[]=addslashes($row->title);
			//$replaceRegex[]='/{article_link}/is';
			//$replaceValue[]=JRoute::_('index.php?option=com_content&view=article&id='.$row->id);
			$replaceRegex[]='/{article_created}/is';
			$replaceValue[]=$row->created;
			$replaceRegex[]='/{article_modified}/is';
			$replaceValue[]=$row->modified;
			$replaceRegex[]='/{article_publish_up}/is';
			$replaceValue[]=$row->publish_up;
			$replaceRegex[]='/{article_rating}/is';
			//get average rating
			$this->db->setQuery( "SELECT rating_sum, rating_count "
			. "FROM #__content_rating "
			. "WHERE content_id='$row->id' "
			. "LIMIT 1 "
			);
			$ratings = $this->db->loadObjectList();
			$rating_ave = '';
			foreach($ratings as $rating){	
				$rating_sum = $rating->rating_sum;
				$rating_count = $rating->rating_count;	
				$rating_ave = floor($rating_sum/$rating_count);				
			}
			$replaceValue[] = $rating_ave;
		}
		
		foreach($fields as $field){
			$field_tag="field_".$field->name."_".$field->field_id;
			if($field->plugin=='image_multisize'){				
				for ($n = 1; $n <= 5; $n++){
					$field->size = $n;
					$value=$this->get_custom_itemtype_field_content($field, $intro_or_full, $readmore_type, $editor_id);
					$replaceRegex[]="/{".$field_tag." size=".$n."}/is"; 
					$replaceValue[] = $value;										
				}
				$field->output = 'alt';
				$value=$this->get_custom_itemtype_field_content($field, $intro_or_full, $readmore_type, $editor_id);
				$field->output = '';
				$replaceRegex[]="/{".$field_tag." output=alt}/is"; 
				$replaceValue[] = $value;				
			}else{
				$value=$this->get_custom_itemtype_field_content($field, $intro_or_full, $readmore_type, $editor_id);				
				if (empty($field->value)){
					$replaceRegex[]="/{if-not-empty_".$field_tag."}(.*?){\/if-not-empty_".$field_tag."}/is";
					$replaceValue[] = '';
					$replaceRegex[]="/{\/?if-empty_".$field_tag."}/is";
					$replaceValue[] = '';
				}else{
					$replaceRegex[]="/{if-empty_".$field_tag."}(.*?){\/if-empty_".$field_tag."}/is";
					$replaceValue[] = '';
					$replaceRegex[]="/{\/?if-not-empty_".$field_tag."}/is";
					$replaceValue[] = '';
				}
				$replaceRegex[]="/{".$field_tag."}/is"; 
				$replaceValue[] = $value;
				
			}			
		}
		
		$html=preg_replace($replaceRegex, $replaceValue, $html);
		
		return $html;
	}
	
	function check_for_read_more_link($fields, $editor_id){
		$is_defined = 0;
		foreach($fields as $field){
			if($field->field_id==$editor_id){				
				$pos1 = strpos($field->value, '<hr id="system-readmore" />');	
				$pos2 = strpos($field->value, '<hr id=\"system-readmore\" />');	
				if($pos1 || $pos2){
					$is_defined = 1;
				}
				break;
			}
		}
		return $is_defined;
	}
	
	function get_custom_itemtype_field_content($field, $intro_or_full, $readmore_type=0, $editor_id=0){
		//explode params
		$html = '';
		$field_params = '';										
		$temp = $field->params;		
		$temp = explode( '[;-)# ]', $temp);	
		for($n = 0; $n < count($temp)-1; $n++){
			list($var,$value) = split('-=-',$temp[$n]); 
			$field_params[$var] = trim($value); 
		}
					
		//explode values									
		$temp = $field->value;
		$temp = explode('[;-)# ]', $temp);	
		for($n = 0; $n < count($temp)-1; $n++){
			list($var,$value) = split('-=-',$temp[$n]); 
			$values[$var] = trim($value); 
		}		
		
		//get output		
		$class_name = 'class_fieldtype_'.$field->plugin;
		$this->include_field_class($field->plugin);	
		$class_plugin = new $class_name();			
		$html .= $class_plugin->render_field_output($field, $intro_or_full, $readmore_type, $editor_id);		
		
		//fix old editors html
		$html = str_replace('<br>','<br />', $html);		
		
		return $html;
	}	
	
	function get_date_now($with_offset){
		//get date and time
		if( defined('_JEXEC') ){
			//joomla 1.5						
			$JApp =& JFactory::getApplication();
			$JDate = JFactory::getDate();			
			jimport('joomla.utilities.date');
			if($with_offset)
			{
				$offset = $JApp->getCfg('offset');
				$summertime = date( 'I' );
				if($summertime)
				{
					$offset = $offset +1;

				}
				//$JDate->setOffset($JApp->getCfg('offset'));
				$JDate->setOffset($offset);
			}	
			$date_now = $JDate->toFormat($this->pi_config['date_format']);						
		}else{
			//joomla 1.0.x
			$date_now = date("Y-m-d H:i:s");
		}
		return $date_now;
	}
	
	function get_date_to_format($date){		
		if( defined('_JEXEC') ){
			//joomla 1.5				
			$JApp =& JFactory::getApplication();
			$date = JFactory::getDate($date);
			
			$offset = $JApp->getCfg('offset');
			$summertime = date( 'I' );
			if($summertime)
			{
				$offset = $offset +1;
			}
			$date->setOffset($offset);
			//$date->setOffset($JApp->getCfg('offset'));	
			$date = $date->toFormat($this->pi_config['date_format']);		
		}
		return $date;
	}
	
	function get_date_ready_for_database($date){		
		if( defined('_JEXEC') ){
			//joomla 1.5
			
			/*
			//Joomla object does not seem to be able to convert this to the correct format ?
			$config =& JFactory::getConfig();
			$tzoffset = $config->getValue('config.offset');
			$date =& JFactory::getDate($date, $tzoffset);			
			$JApp =& JFactory::getApplication();			
			$offset = $JApp->getCfg('offset');
			$summertime = date( 'I' );
			if($summertime){
				$offset = $offset +1;
			}
			$date = JFactory::getDate($date, $offset); 			
			$date = JFactory::getDate($date, 0);
			$date = $date->toFormat("%Y %m %d %H:%M:%S");			
			$date = $date->toMySQL();			
			*/
			
			//get date format
			$dateformat = $this->pi_config['date_format'];
			$dateformat_array = explode('-', $dateformat);			
			$date_array = explode('-', $date);
						
			$year = 0;
			$month = 0;
			$day = 0;
			for($n = 0; $n < 3; $n++){				
				$dateformat_row = strtolower($dateformat_array[$n]);
				if(strpos($dateformat_row, 'y')){
					$year = intval($date_array[$n]);
				}
				if(strpos($dateformat_row, 'm')){
					$month = intval($date_array[$n]);
				}
				if(strpos($dateformat_row, 'd')){
					$day = intval($date_array[$n]);
				}				
			}			
			$timestamp = mktime(0,0,0,$month,$day,$year);			
			$date = date("Y-m-d 00:00:00", $timestamp);			
		}
		return $date;
	}

	
	function include_field_class($plugin){
		$class_name = 'class_fieldtype_'.$plugin;
	
		//echo $class_name;
		if(!class_exists($class_name)){
			if(in_array($plugin, $this->fieldtypes_integrated)){
				//integrated field type
				require_once(dirname(__FILE__).'/class_custom_item_types.php');								
			}else{
				if( defined('_JEXEC') ){
					//joomla 1.5
					$dir = 'plugins';
				}else{
					//joomla 1.0.x
					$dir = 'mambots';
				}
				require_once(dirname(__FILE__).'/../../../'.$dir.'/pages_and_items/fieldtypes/'.$plugin.'/'.$plugin.'.php');				
			}
		}
	}
	
	function display_field($field_name, $field_content, $width_left='20', $width_right='70'){
		$html = '<div class="pi_form_wrapper">';
		$html .= '<div class="pi_width'.$width_left.'">';		
		$has_only_star = strpos($field_name, 'img src=');
		if($field_name!='' && $has_only_star!=1){
			$html .= $field_name.':';
		}elseif($has_only_star==1){
			$html .= $field_name;
		}else{
			$html .= '&nbsp;';
		}
		$html .= '</div>';
		$html .= '<div class="pi_width'.$width_right.'">';
		$html .= $field_content;
		$html .= '</div>';
		$html .= '</div>';
		return $html;
	}
	
	function display_field_description($field_params){
		//$field_name = strtolower(_pi_lang_description);
		//changed on request of Micha for German chapital letters.
		$field_name = _pi_lang_description;
		$field_content = '<input type="text" class="width200" value="'.$field_params['description'].'" name="field_params[description]" />';		
		return $this->display_field($field_name, $field_content);
	}
	
	function display_field_validation($field_params){
		$field_name = _pi_lang_validation;
		$field_content = '<input type="checkbox" class="checkbox"';
		//if($field_params['validation']){
		if($this->check_if_field_param_is_present($field_params, 'validation')){
			if($field_params['validation']){
				$field_content .= ' checked="checked"';
			}
		} 
		$field_content .= 'name="field_params[validation]" value="not_empty" /> '._pi_lang_not_empty;		
		return $this->display_field($field_name, $field_content);
	}
	
	function check_if_field_param_is_present($field_params, $field_param){
		$param_is_present = false;
		for($n = 0; $n < count($field_params); $n++){											
			$row = each($field_params);
			if($row['key']==$field_param){
				$param_is_present = true;
				break;
			}											
		}
		return $param_is_present;
	}	
	
	function check_if_plugin_lang_var_is_present($pi_lang_plugin, $var){
		$var_is_present = false;
		for($n = 0; $n < count($pi_lang_plugin); $n++){											
			$row = each($pi_lang_plugin);
			if($row['key']==$var){
				$var_is_present = true;
				break;
			}											
		}
		return $var_is_present;
	}	
	
	function display_field_validation_message($field_params){
		$field_content = '<input type="text" class="width200" value="'.$field_params['alert_message'].'" name="field_params[alert_message]" />';
		return $this->display_field(_pi_lang_validation_alert_message, $field_content);
	}
	
	function display_field_default_value($field_params){
		$field_content = '<input type="text" class="width200" value="'.$field_params['default_value'].'" name="field_params[default_value]" />';
		return $this->display_field(_pi_lang_default_value, $field_content);
	}
	
	function get_field_value($values_string, $property){
		$values_array = explode('[;-)# ]', $values_string);		
		$property = substr($property,1);
		$html = '';		
		foreach($values_array as $value_set){
			if(strpos($value_set, $property)){
				$temp = explode('-=-', $value_set);
				$html = $temp[1];
				break;
			}
		}
		return $html;
	}
	
	function get_field_param($values_string, $property){
		return $this->get_field_value($values_string, $property);
	}
	
	function get_page_id_from_item_id($item_id){	
	
		$cat_id = $this->get_cat_id_from_item($item_id);
		
		//get menuitems. I need to get these in a new query because calling $this->menuitems does not work when called from class_custom_item_types.php why I do not know.
		$this->db->setQuery( "SELECT id, link, type FROM #__menu ");
		$menuitems = $this->db->loadObjectList();
		
		$original_page_id = false;
		foreach($menuitems as $menu_item_page){
			$temp_cat_id = 0;
			//if category blog
			if((defined('_JEXEC') && strstr($menu_item_page->link, 'index.php?option=com_content&view=category&layout=blog') && $menu_item_page->type!='url' && $menu_item_page->type=='component') ||
			(!defined('_JEXEC') && $menu_item_page->type=='content_blog_category')
			){			
				//get the category id of each menu item				
				$pos_cat_id = strpos($menu_item_page->link,'id=');
				$temp_cat_id = substr($menu_item_page->link, ($pos_cat_id+3), strlen($menu_item_page->link));
				if($cat_id==$temp_cat_id){				
					$original_page_id = $menu_item_page->id;
					break;
				}
			}elseif(strstr($menu_item_page->link, 'index.php?option=com_content&view=article&id='.$item_id) || strstr($menu_item_page->link, 'index.php?option=com_content&task=view&id='.$item_id)){
				//full item layout
				$original_page_id = $menu_item_page->id;
				break;
			}
		}		
		return $original_page_id;
	}
	
	function get_cat_id_from_item($item_id){
		$this->db->setQuery( "SELECT catid FROM #__content WHERE id='$item_id' LIMIT 1 ");
		$items = $this->db->loadObjectList();
		$catid = false;
		foreach($items as $item){
			$catid = $item->catid;
		}
		return $catid;
	}
	
	function get_fieldtype_language($fieldtype){
		if(!in_array($fieldtype, $this->fieldtypes_integrated)){
			if(file_exists(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$fieldtype.'/language/'.$this->pi_config['language'].'.php')){
				require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$fieldtype.'/language/'.$this->pi_config['language'].'.php'); 
			}else{				
				if(file_exists(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$fieldtype.'/language/english.php')){
					require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/fieldtypes/'.$fieldtype.'/language/english.php'); 
				}
			}
		}
	}	
	
	function check_display_item_property($property, $right){
		$display = false;		
		if($this->pi_config['use_user_access_component'] && $this->user_access_config['active_actions'] && $this->user_access_config['item_props'] && $this->user_type!='Super Administrator'){
			//use Admin-User-Access to check for workflow right			
			if($this->class_ua->check_workflow($right, $this->usergroup)){
				$display = true;
			}
		}elseif($this->user_type=='Super Administrator' && !$this->pi_config['item_props_hideforsuperadmin']){		
			$display = true;
		}else{
			//check configuration
			if($this->pi_config[$property]){
				$display = true;
			}			
		}
		//$display = true;
		return $display;
	}
	
	function get_username(){
		$user_id = $this->user_id;
		$this->db->setQuery("SELECT username "
		."FROM #__users "
		."WHERE id='$user_id' "
		."LIMIT 1 "		
		);
		$users = $this->db->loadObjectList();
		$user = $users[0];		
		return $user->username;
	}
	
	function get_sublevel_add_one($menu_id){
		$sublevel = 0;
		if(defined('_JEXEC')){				
			foreach($this->menuitems as $menuitem){
				if($menuitem->id==$menu_id){
					$sublevel = $menuitem->sublevel+1;					
					break;
				}
			}
		}		
		return $sublevel;
	}
	
	function include_itemtype_class($item_type){
		$class_name = 'class_itemtype_'.$item_type;
	
		if(!class_exists($class_name)){			
			require_once(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/itemtypes/'.$item_type.'/'.$item_type.'.php');				
		}
	}
	

	function get_itemtype_language($item_type){	
		$pi_lang_plugin = array();
		//include(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/itemtypes/'.$item_type.'/language/english.php');	
		if(file_exists(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/itemtypes/'.$item_type.'/language/'.$this->pi_config['language'].'.php')){
			include(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/itemtypes/'.$item_type.'/language/'.$this->pi_config['language'].'.php'); 
		}else{				
			if(file_exists(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/itemtypes/'.$item_type.'/language/english.php')){
				include(dirname(__FILE__).'/../../../'.$this->plugin_dir.'/pages_and_items/itemtypes/'.$item_type.'/language/english.php'); 
			}
		}		
		return $pi_lang_plugin;
	}
	
	function unlock_item($item_id){		
		$this->db->setQuery( "UPDATE #__content SET checked_out='0', checked_out_time='0' WHERE id='$item_id' "	);
		$this->db->query();				
	}	
	
	function check_display_page_property($property, $right){
		$display = false;		
		if($this->pi_config['use_user_access_component'] && $this->user_access_config['active_actions'] && $this->user_access_config['page_props'] && $this->user_type!='Super Administrator'){
			//use Admin-User-Access to check for workflow right			
			if($this->class_ua->check_workflow($right, $this->usergroup)){
				$display = true;
			}
		}elseif($this->user_type=='Super Administrator' && !$this->pi_config['page_props_hideforsuperadmin']){	
			$display = true;
		}else{
			//check configuration
			if($this->pi_config[$property]){
				$display = true;
			}			
		}		
		return $display;
	}
	
	function get_config(){		
		
		$this->db->setQuery("SELECT config "
		."FROM #__pi_config "
		."WHERE id='pi' "
		."LIMIT 1"
		);
		$temp = $this->db->loadObjectList();
		$temp = $temp[0];
		$raw = $temp->config;	
		
		//get page attributes		
		$pos_start_page_attribs = strpos($raw, 'START_PAGE_NEW_ATTRIBUTES');
		$start_of_vars = $pos_start_page_attribs+26;
		$page_new_attribs = substr($raw, $start_of_vars, 99999);		
		$pi_config['page_new_attribs'] = $page_new_attribs;		
		
		//get just the config vars
		$rest_of_config = substr($raw, 0, $pos_start_page_attribs);
		
		$params = explode( "\n", $rest_of_config);
		
		for($n = 0; $n < count($params); $n++){		
			$temp = explode('=',$params[$n]);
			$var = $temp[0];
			$value = '';
			if(count($temp)==2){
				$value = trim($temp[1]);
				if($value=='false'){
					$value = false;
				}
				if($value=='true'){
					$value = true;
				}
			}							
			$pi_config[$var] = $value;	
		}		
		return $pi_config;			
	}
	
	function get_config_admin_user_access(){
			
		$this->db->setQuery("SELECT config "
		."FROM #__pi_aua_config "
		."WHERE id='aua' "
		."LIMIT 1"
		);
		$temp = $this->db->loadObjectList();
		$temp = $temp[0];
		$raw = $temp->config;
		
		$params = explode( "\n", $raw);
		
		for($n = 0; $n < count($params); $n++){		
			$temp = explode('=',$params[$n]);
			$var = $temp[0];
			$value = '';
			if(count($temp)==2){
				$value = trim($temp[1]);
				if($value=='false'){
					$value = false;
				}
				if($value=='true'){
					$value = true;
				}
			}							
			$config[$var] = trim($value);	
		}
		
		return $config;
	}
	
	function get_itemtype_config($item_type){	
	
		//get plugin-specific config	
		if(defined('_JEXEC')){
			//joomla 1.5
			$pluginstable = 'plugins';
			$database = JFactory::getDBO();
		}else{
			//joomla 1.0.x
			$pluginstable = 'mambots';
			global $database;
		}	
		
		$database->setQuery( "SELECT params FROM #__".$pluginstable." WHERE element='itemtype_".$item_type."' LIMIT 1 ");		
		$temp = $database->loadObjectList();
		$temp = $temp[0];
		$raw = $temp->params;
		
		//make string to array
		$params = explode( "\n", $raw);
		for($n = 0; $n < count($params); $n++){		
			$temp = explode('=',$params[$n]);
			$var = $temp[0];
			$value = '';
			if(count($temp)==2){
				$value = trim($temp[1]);
				if($value=='false'){
					$value = false;
				}
				if($value=='true'){
					$value = true;
				}
			}							
			$plugin_config[$var] = $value;	
		}		
		return $plugin_config;	
	}
	
	function return_field_value($item_id, $field_id){		
					
		//get values	
		$this->db->setQuery("SELECT value "
		."FROM #__pi_custom_fields_values "
		."WHERE field_id='$field_id' AND item_id='$item_id' "
		."LIMIT 1"
		);								
		$rows = $this->db->loadObjectList();
		$html = '';
		foreach($rows as $row){
			$html = $row->value;
		}				
		
		//fix old editors html
		$html = str_replace('<br>','<br />', $html);		
		
		return $html;		
	}	
	
	/*
	function template_property($field, $property){
		$properties_string = ' '.$field->template_properties;		
		if(strpos($properties_string, $property)){			
			$properties_array = explode(' ', $properties_string);
			for($n = 0; $n < count($properties_array); $n++){	
				$property_array = explode('=', $properties_array[$n]);
				$temp_property = $property_array[0];
				if($temp_property==$property){
					$property_value = $property_array[1];
				}
			}			
		}else{
			$property_value = false;
		}		
		return $property_value;
	}
	*/
	
	function clean_cache_menu(){
		if(defined('_JEXEC')){
			//joomla 1.5
			global $mainframe;
			
			if ($mainframe->getCfg('caching')) {
			
				// clean system cache
				$cache =& JFactory::getCache('_system');
				$cache->clean();
				
				// clean mod_mainmenu cache
				$cache2 =& JFactory::getCache('mod_mainmenu');
				$cache2->clean();
			}
		}
	}
	
	function clean_cache_content(){
		if(defined('_JEXEC')){
			//joomla 1.5
			global $mainframe;
			
			if ($mainframe->getCfg('caching')) {
				
				//clean content cache
				$cache = & JFactory::getCache('com_content');
				$cache->clean();
					
			}
		}
	}
	
	function ajax_update_cit_item(){
		$itemtype = intval($this->get_var('itemtype',''));
		$item_id = intval($this->get_var('item_id',''));
		$itemtype_name = 'custom_'.$itemtype;
		
		//echo 'return from ajax'.$itemtype.' '.$item_id;
		$this->update_content_table_from_custom_itemtype($item_id, $itemtype_name);
		//check if the saved item has other_items linked to it, if so, update those			
		$this->update_other_items_if_needed($item_id);
		echo '<span style="color: #5F9E30;">'._pi_lang_updated.'</span>';
		exit;
	}
	
	function make_alias_unique($alias, $tablename, $exclude_id){
		
		//get aliasses, except for the current alias-row
		$where = '';
		if($exclude_id){
			$where = "WHERE id<>$exclude_id  ";
		}		
		$this->db->setQuery("SELECT alias "
		."FROM #__$tablename "	
		.$where	
		);
		$rows = $this->db->loadObjectList();		
		$aliasses = array();
		foreach($rows as $row){	
			$aliasses[] = $row->alias;	
		}
		
		if(in_array($alias, $aliasses)){			
			$j = 2;			
			while (in_array($alias."-".$j, $aliasses)){				
				$j = $j + 1;
			}
			$alias = $alias."-".$j;	
		}
		
		return $alias;	
	}
	
	function ajax_make_menu_alias_unique(){
		
		$updated = 0;
		
		if(defined('_JEXEC')){
			//joomla 1.5 joomla 1.x does not have aliasses in menu table

			$menu_item_id = intval($this->get_var('menu_item_id',''));
			
			$menu_alias_ori = '';
			//get aliasses		
			$this->db->setQuery("SELECT id, alias "
			."FROM #__menu "				
			);
			$rows = $this->db->loadObjectList();		
			$aliasses = array();
			foreach($rows as $row){	
				if($row->id==$menu_item_id){
					$menu_alias_ori = $row->alias;
				}else{
					$aliasses[] = $row->alias;	
				}
			}
			$menu_alias = $menu_alias_ori;
			if(in_array($menu_alias, $aliasses)){			
				$j = 2;			
				while (in_array($menu_alias."-".$j, $aliasses)){				
					$j = $j + 1;
				}
				$menu_alias = $menu_alias."-".$j;	
			}
			
			if($menu_alias!=$menu_alias_ori){
				//do update
				$this->db->setQuery( "UPDATE #__menu SET alias='$menu_alias' WHERE id='$menu_item_id' ");
				$this->db->query();
				$updated = 1;
			}
		
		}
		
		$message = _pi_lang_alias_is_ok;
		if($updated){
			$message = _pi_lang_updated.': '.$menu_alias;
		}
		
		echo '<span style="color: ';
		if($updated){
			echo 'red';	
		}else{
			echo '#5F9E30';
		}
		echo ';">'.$message.'</span>';
		exit;
	}
	
	function acesef_item($acesef_url_id, $page_id, $cat_id, $item_id, $title, $metadesc, $metakey, $alias){
	
		//only if acesef is installed
		if(!file_exists(dirname(__FILE__).'/../com_acesef/controller.php')){
			return true;
		}
	
		//category stuff
		$cat_alias = '';
		if($this->pi_config['sef_url_cat']){
			$this->db->setQuery("SELECT alias "
			."FROM #__categories "
			."WHERE id='$cat_id' "
			."LIMIT 1 "
			);
			$rows = $this->db->loadObjectList();
			foreach($rows as $row){	
				$cat_alias = $row->alias;	
			}
		}
		
		//item id stuff
		$item_id_sef = '';
		if($this->pi_config['sef_url_id']){
			$item_id_sef = $item_id.'-';		
		}
		
		//suffix stuff
		$suffix = '';
		if($this->pi_config['sef_url_ext']){
			$suffix = $this->pi_config['sef_url_ext'];		
		}
				
		$url_sef = $cat_alias.'/'.$item_id_sef.$alias.$suffix;
		$url_real = 'index.php?option=com_content&Itemid='.$page_id.'&catid='.$cat_id.'&id='.$item_id.'&view=article';
		$acesef_metatitle = $this->get_var('acesef_metatitle', '', 'post');		
		$acesef_metatitle = addslashes($acesef_metatitle);	
		if($acesef_metatitle==''){
			$acesef_metatitle = $title;
		}		
			
		if(!$acesef_url_id){
			//insert the url
			$this->db->setQuery( "INSERT INTO #__acesef_urls SET url_sef='$url_sef', url_real='$url_real', metatitle='$acesef_metatitle', metadesc='$metadesc', metakey='$metakey', published='1' ");
			$this->db->query();
		}else{
			//update the url
			$this->db->setQuery( "UPDATE #__acesef_urls SET url_sef='$url_sef', url_real='$url_real', metatitle='$acesef_metatitle', metadesc='$metadesc', metakey='$metakey' WHERE id='$acesef_url_id'");
			$this->db->query();
		}
	}


}

?>